## OpenCA - Command
## (c) 1998-2001 by Massimiliano Pala and OpenCA Group
##
##   File Name: viewCRR
##       Brief: View CRR
## Description: Display given CRR to the RA Operator
##  Parameters: dataType, key

sub cmdViewCRR {

## Get the Configuration parameters ...
my ( $ou, $ouList, $def, $op, $opCert, $info, $opStatus, $dnLabel);
my ( $sigStatus, $signer, $signature, $myCN, $myEmail, @myDnInfo, $subjectAltName );
my ( @opCertList, $reqDataTable, @cols, $opCert, $serLink, $lnk, $sigInfo );
my ( %labels, @values, $role );
my ( $reqStatus, $cmdsPanel, $reqDesc );

my $dataType = $query->param('dataType' );
my $key      = $query->param('key');

## Required Configuration Key
my $sheetsDir	= getRequired( 'SheetsDir' );
my $includeDir	= getRequired( 'IncludeDir' );
my $txtDir	= getRequired( 'TextDir' );
my $baseDoc     = getRequired('ViewCRRSheet');

configError( gettext("Error, needed dB key!") ) if ( not $key );

if ( $dataType eq "PENDING_CRR" ) {
	$reqStatus = gettext("Revocation Request Waiting for Approval");
	$cmdsPanel = "$includeDir/pending_crr_cmds.inc";
	$reqDesc   = "$txtDir/pending_crr_desc.txt";
} elsif ( $dataType eq "APPROVED_CRR" ) {
	$reqStatus = gettext("Approved Revocation Request");
	$cmdsPanel = "$includeDir/approved_crr_cmds.inc";
	$reqDesc   = "$txtDir/approved_crr_desc.txt";
} elsif ( $dataType eq "ARCHIVED_CRR" ) {
	$reqStatus = gettext("Archived Revocation Request");
	$cmdsPanel = "$includeDir/archived_crr_cmds.inc";
	$reqDesc   = "$txtDir/archived_crr_desc.txt";
} elsif ( $dataType eq "DELETED_CRR" ) {
	$reqStatus = gettext("Deleted Revocation Request");
	$cmdsPanel = "$includeDir/deleted_crr_cmds.inc";
	$reqDesc   = "$txtDir/deleted_crr_desc.txt";
} elsif ( $dataType eq "CRR" ) {
        ## try to determine the datatype
        if ($db->getItem ( DATATYPE => "ARCHIVED_CRR", KEY => $key )) {
                $dataType = "ARCHIVED_CRR";
                $reqStatus = gettext ("Archived Revocation Request");
                $cmdsPanel = "$includeDir/archived_crr_cmds.inc";
                $reqDesc   = "$txtDir/archived_crr_desc.txt";
        } elsif ($db->getItem ( DATATYPE => "APPROVED_CRR", KEY => $key )) {
                $dataType = "APPROVED_CRR";
                $reqStatus = gettext ("Approved Revocation Request");
                $cmdsPanel = "$includeDir/approved_crr_cmds.inc";
                $reqDesc   = "$txtDir/approved_crr_desc.txt";
        } elsif ($db->getItem ( DATATYPE => "DELETED_CRR", KEY => $key )) {
                $dataType = "DELETED_CRR";
                $reqStatus = gettext ("Deleted Revocation Request");
                $cmdsPanel = "$includeDir/deleted_crr_cmds.inc";
                $reqDesc   = "$txtDir/deleted_crr_desc.txt";
        } elsif ($db->getItem ( DATATYPE => "PENDING_CRR", KEY => $key )) {
                $dataType = "PENDING_CRR";
                $reqStatus = gettext("Revocation Request Waiting for Approval");
                $cmdsPanel = "$includeDir/pending_crr_cmds.inc";
                $reqDesc   = "$txtDir/pending_crr_desc.txt";
        } else {
                configError ( gettext ("Cannot determine status of this request!"));
        }
} else {
	configError ( i18nGettext ("Invalid or missing dataType (__DATATYPE__)!", "__DATATYPE__", $dataType));
}

if( not ( $page = $query->getFile( $baseDoc )) ) {
	configError ( i18nGettext ("Error while loading file __FILE__!", "__FILE__", $baseDoc) );
};

## Substitute the cmdsPanel, reqStatus and reqDesc
$page = $query->subVar( $page, '@STATUS@', $reqStatus );
$page = $query->subVar( $page, '@REQDESC@', $tools->getFile( "$reqDesc") );
$page = $query->subVar( $page, '@CMDSPANEL@', $tools->getFile("$cmdsPanel") );

my $req = $db->getItem( DATATYPE=>$dataType, KEY=>$key );

configError ( gettext("CRR not present in DB!") ) if ( not $req );

## Get the parsed Request
my $parsed_req = $req->getParsed();

########################################
## begin to build request for signing ##
########################################

my ($header, $text);
my $beginHeader = "-----BEGIN HEADER-----";
my $endHeader = "-----END HEADER-----";

## build header
$header  = "$beginHeader\n";
$header .= "TYPE = CRR\n";
$header .= "SERIAL = $key\n";
$header .= "SSL_CERT_SERIAL = ".$req->getParsed()->{HEADER}->{SSL_CERT_SERIAL}."\n";
$header .= "SSL_CERT_DN = ".$req->getParsed()->{HEADER}->{SSL_CERT_DN}."\n";
$header .= "SSL_CERT_ISSUER = ".$req->getParsed()->{HEADER}->{SSL_CERT_ISSUER}."\n";
$header .= "$endHeader\n";
## build body
$text  = "SUBMIT_DATE = " . $req->getParsed()->{SUBMIT_DATE}. "\n";
$text .= "APPROVED_DATE = " . $tools->getDate() . "\n";
$text .= "CRIN = ".$req->getParsed()->{CRIN}."\n";
$text .= "REVOKE_REASON = $reason\n";
$text .= "REVOKE_CERTIFICATE_DN = " . $req->getParsed()->{REVOKE_CERTIFICATE_DN} . "\n";
$text .= "REVOKE_CERTIFICATE_NOTBEFORE = " . $req->getParsed()->{REVOKE_CERTIFICATE_NOTBEFORE} . "\n";
$text .= "REVOKE_CERTIFICATE_NOTAFTER = " . $req->getParsed()->{REVOKE_CERTIFICATE_NOTAFTER} . "\n";
$text .= "REVOKE_CERTIFICATE_SERIAL = " . $req->getParsed()->{REVOKE_CERTIFICATE_SERIAL} . "\n";
$text .= "REVOKE_CERTIFICATE_ISSUER_DN = " . $req->getParsed()->{REVOKE_CERTIFICATE_ISSUER_DN} . "\n";
$text .= "REVOKE_CERTIFICATE_KEY_DIGEST = " . $req->getParsed()->{REVOKE_CERTIFICATE_KEY_DIGEST} . "\n";

$page = $query->subVar( $page, '@HEADER@', "" );
$page = $query->subVar( $page, '@TEXT@',   $header.$text );

######################################
## end to build request for signing ##
######################################

@cols = ( gettext("Variable"), gettext("Value") );
$reqDataTable = $query->startTable( COLS=>[ @cols ],
                                        WIDTH=>"100%",
                                        ## BGCOLOR=>"#F1F0F8",
					PADDING=>"2",
					CELLPADDING=>"4",
					TABLE_BGCOLOR=>"#F1F0F8",
                                        TITLE_BGCOLOR=>"#DDCCFF" );

## which cert should be revoked
my $cert = $db->getItem (DATATYPE => "CERTIFICATE", KEY => $req->getParsed()->{REVOKE_CERTIFICATE_SERIAL});
if ($cert) {
	if (  $cert->getParsed()->{DN_HASH}->{CN}[0] ne "" ) {
		$lnk = new CGI({cmd=>"search", dataType=>"CERTIFICATE",
				name=>"CN", value=>$cert->getParsed()->{DN_HASH}->{CN}[0]} );
		$myCN = $lnk->a({-href=>$lnk->self_url()}, $cert->getParsed()->{DN_HASH}->{CN}[0]);
	}

	if (  $cert->getParsed()->{EMAILADDRESS} ne "" ) {
		$lnk = new CGI({cmd=>"search", dataType=>"CERTIFICATE",
				name=>"EMAIL", value=>$cert->getParsed()->{EMAILADDRESS}} );
		$myEmail = $lnk->a({-href=>$lnk->self_url()}, $cert->getParsed()->{EMAILADDRESS});
	};
};

## check signature
if ( $req->getParsed()->{TYPE} =~ /with .*? Signature/i ) {

	$lnk = new CGI({cmd=>"viewSignature", dataType=>$dataType, key=>$key});
	if( libCheckSignature( OBJECT=>$req ) ) {
		$tmp = $query->img({src=>getRequired ('ValidSigImage'),
					border=>"0", align=>"MIDDLE"});
	} else {
		$tmp = $query->img({-src=>getRequired ('SigErrorImage'),
					-border=>"0", -align=>"MIDDLE"});
	}

	$sigInfo = $lnk->a({-href=>$lnk->self_url()}, $tmp );
	
} else {
	$def = "<FONT COLOR=\"RED\">".gettext("Not Signed")."</FONT>";
	$parsed_req->{OPERATOR} = $def;
}

## try to get the issuer of the CRR
my $submit;
if ($parsed_req->{SIGNATURE}) {
	## signature-based revocation
	if (my $sig = libGetSignatureObject ( OBJECT => $req )) {
		if (my $cert = libGetSignerCertificateDB( SIGNATURE=> $sig )) {
			$submit = $cert->getParsed()->{DN};
		} else {
			$submit = gettext("Cannot determine certificate from signature!");
			print STDERR "Cannot determine certificate from signature (CRR: ".$req->getSerial ().")\n";
		}
	} else {
		$submit = gettext ("Cannot build object from signature!");
		print STDERR "Cannot build object from signature (CRR: ".$req->getSerial ().")\n";
	}
} elsif ($parsed->{REVOKE_CERTIFICATE_DN}) {
	## pin-based revocation
	$submit = $parsed_req->{REVOKE_CERTIFICATE_DN};
} else {
	## last chance by strong ssl-authentication
	$submit = $head->{SSL_CERT_DN};
	print STDERR "submitter of CRR not determinable (CRR: $key)\n";
}

## $reqDataTable .=$query->addTableLine(DATA=>[ "<B>:</B>",
## 			($parsed_req->{} or "n/a") ]);
$reqDataTable .=$query->addTableLine(DATA=>["<B>".gettext("Request Version:")."</B>",
                        ($parsed_req->{VERSION} or gettext("n/a")) ]);
$reqDataTable .=$query->addTableLine(DATA=>[ "<B>".gettext("CRR Serial Number:")."</B>",
                        ($req->getSerial() or gettext("n/a")) ]);
$reqDataTable .=$query->addTableLine(DATA=>["<B>".gettext("Request Type:")."</B>",
                        ($parsed_req->{TYPE} or gettext("n/a")) ]);
$reqDataTable .=$query->addTableLine(DATA=>["<B>".gettext("Submission Date:")."</B>",
			($parsed_req->{SUBMIT_DATE} or gettext("n/a")) ]);
$reqDataTable .=$query->addTableLine(DATA=>["<B>".gettext("Submitter:")."</B>",
			($submit or gettext("n/a")) ]);
$reqDataTable .=$query->addTableLine(DATA=>[ "<B>".gettext("Reason:")."</B>",
                        ($parsed_req->{REVOKE_REASON} or gettext("n/a")) ]);
$reqDataTable .=$query->addTableLine(DATA=>[ "<B>".gettext("Common Name:")."</B>",
			($myCN or gettext("n/a")) ]);
$reqDataTable .=$query->addTableLine(DATA=>[ "<B>".gettext("E-Mail:")."</B>",
			($myEmail or gettext("n/a")) ]);
$reqDataTable .=$query->addTableLine(DATA=>[ "<B>".gettext("Role:")."</B>",
			$cert->getParsed()->{HEADER}->{ROLE} ]);
$reqDataTable .=$query->addTableLine(DATA=>[ "<B>".gettext("Distinguished Name:")."</B>",
                        ($cert->getParsed()->{DN} or gettext("n/a")) ]);
$reqDataTable .=$query->addTableLine(DATA=>[ "<B>".gettext("Approved on:")."</B>",
                        ($parsed_req->{APPROVED_DATE} or gettext("n/a")) ]);
$reqDataTable.=$query->addTableLine(DATA=>["<B>".gettext("Used Identification PIN:")."</B>",
                        ($parsed_req->{CRIN} or gettext("n/a")) ]);
$reqDataTable .=$query->addTableLine(DATA=>[ "<B>".gettext("Signature Algorithm:")."</B>",
                        ($parsed_req->{SIG_ALGORITHM} or gettext("n/a")) ]);

$reqDataTable .= $query->endTable();

$page = $query->subVar( $page, '@REQDATA@', $reqDataTable );

## Substitute dB coordinates
$page = $query->subVar( $page, '@DATATYPE@', $dataType );
$page = $query->subVar( $page, '@KEY@', $key );

## View the Signature Logo
$page = $query->subVar( $page, '@SIGINFO@',    $sigInfo );

print "$page";

}

1;
