<?php
// #######################################################
// Author: Martin Haase / DAASI International GmbH / TextGrid
// Creation date: 2010-10-19
// Modification date: 2010-XX
// Version: 0.1
// #######################################################

include("../tglib/RBAC.class.php");
include("../tglib/WebUtils.class.php");

$configfile = "../../../config_tgwebauth.xml";

$util = new WebUtils;

$authZinstance = $_REQUEST["authZinstance"];
$remote_user = $_REQUEST["remote_user"];

if ($_REQUEST["loginmode"] == 1) {
  $loginmode = TRUE;
} else {
  $loginmode = FALSE;
}

if ( !(isset($authZinstance)) || strlen($authZinstance) <= 0 ) {
  $util->printAuthFailure("No TgAuth Instance provided", 
		      "Please provide a valid string in the authZinstance variable.", 
		      null, 
		      null );
  exit;
}

$rbac = new RBAC ( $configfile, $authZinstance );

$Sid = $_REQUEST["Sid"];

$attributes = $rbac->getUserAttributes( $Sid );
$newattributes = array();
$thedisplayname = "anonymous";

//phpinfo(); 
foreach ($attributes as $a) {
  if ($util->isBoolean($a)) {
    if (isset ( $_REQUEST[$a->name]) && $_REQUEST[$a->name] == TRUE) {
      $na = new StdClass();
      $na->name = $a->name;
      $na->value = "TRUE";
      $newattributes[] = $na;
    } else {
      $na = new StdClass();
      $na->name = $a->name;
      $na->value = "FALSE";
      $newattributes[] = $na;
    }
  } else if (isset ( $_REQUEST[$a->name]) 
	     && strlen($_REQUEST[$a->name]) > 0 
	     && (!isset ($a->value) 
		 || ( isset( $a->value) 
		      && !($_REQUEST[$a->name] === $a->value)))) {
    $na = new StdClass();
    $na->name = $a->name;
    $na->value = $_REQUEST[$a->name];
    $newattributes[] = $na;
  }
  if ($a->name === "displayname" && isset ($a->value)) { // set Display Name
    $thedisplayname = $a->value;
  }
}

$res = $rbac->setAttributes($newattributes, $Sid, $loginmode );
if ((is_array($res) && $res['success'] == FALSE) || (is_object($res) && $res->result == FALSE)) {
  echo "something went wrong". serialize($res);
  exit;
}

if ($loginmode) {
  $util->printAuthSuccess("Authentication Succeeded",
			  $thedisplayname,
			  array("remote_user" => $remote_user,
				"scstatus" => "set Attributes",
				"Sid" => $Sid,
				"rbacbase" => $authZinstance,
				"identity_provider" => "unknown",
				"identified_user" => array("authnmethod" => "ePPN")
				),
			  array("slcmode" => FALSE) // SLCs only via Shibboleth
			  ); 
} else {
  $util->printSetAttributesSuccess($thedisplayname);
}
exit;

?>