## OpenCA - Command
## (c) 1998-2001 by Massimiliano Pala and OpenCA Group
##
##   File Name: viewCert
##       Brief: Display a certificate
##// Description: Display a certificate's data
##  Parameters: dataType, key

sub cmdViewCert {

##Reseved Variables
my ( @cols, $doc, $date, $sheet, $myType );

## Get the Serial Number
my $key      = $query->param( 'key' );
my $dataType = $query->param( 'dataType' );
my $date     = $tools->getDate();
my $server   = getRequired ('CgiServerType');

my @certDataTypes = ( VALID_CERTIFICATE, EXPIRED_CERTIFICATE,
                              REVOKED_CERTIFICATE );

if( not $key and ($key != 0)) {
	configError( gettext ("Error, missing key!") );
}

if ( not $dataType ) {
	$dataType = "CERTIFICATE";
}

if ( $dataType =~ /^VALID_CERTIFICATE/ ) {
	$status = gettext ("Valid");
} elsif ( $dataType =~ /^EXPIRED_CERTIFICATE/ ) {
	$status = gettext("Expired");
} elsif ( $dataType =~ /^SUSPENDED_CERTIFICATE/ ) {
	$status = gettext("Suspended");
} elsif ( $dataType =~ /^REVOKED_CERTIFICATE/ ) {
	$status = gettext("Revoked");
} elsif ( $dataType =~ /^VALID_CA_CERTIFICATE/ ) {
	$status = gettext("Valid");
} elsif ( $dataType =~ /^EXPIRED_CA_CERTIFICATE/ ) {
	$status = gettext("Expired");
} elsif ( $dataType =~ /^CA_CERTIFICATE/ ) {
	## try to determine the datatype
	if ($db->getItem ( DATATYPE => "VALID_CA_CERTIFICATE", KEY => $key )) {
		$dataType = "VALID_CA_CERTIFICATE";
		$status   = gettext("Valid");
	} elsif ($db->getItem ( DATATYPE => "EXPIRED_CA_CERTIFICATE", KEY => $key )) {
		$dataType = "EXPIRED_CA_CERTIFICATE";
		$status   = gettext("Expired");
	} else {
		configError ( gettext ("Cannot determine status of this CA-Certificate!"));
	}
} elsif ( $dataType =~ /^CERTIFICATE/ ) {
	## try to determine the datatype
	if ($db->getItem ( DATATYPE => "VALID_CERTIFICATE", KEY => $key )) {
		$dataType = "VALID_CERTIFICATE";
		$status   = gettext("Valid");
	} elsif ($db->getItem ( DATATYPE => "EXPIRED_CERTIFICATE", KEY => $key )) {
		$dataType = "EXPIRED_CERTIFICATE";
		$status   = gettext("Expired");
	} elsif ($db->getItem ( DATATYPE => "SUSPENDED_CERTIFICATE", KEY => $key )) {
		$dataType = "SUSPENDED_CERTIFICATE";
		$status   = gettext("Suspended");
	} elsif ($db->getItem ( DATATYPE => "REVOKED_CERTIFICATE", KEY => $key )) {
		$dataType = "REVOKED_CERTIFICATE";
		$status   = gettext("Revoked");
	} else {
		configError ( gettext ("Cannot determine status of this Certificate!"));
	}
} else {
	configError (i18nGettext ("DataType not supported (__DATATYPE__)!", "__DATATYPE__", $dataType));
}

## Get Required Param
if( $dataType =~ /(VALID|EXPIRED|SUSPENDED)_CERTIFICATE/ ) {
	$sheet    = getRequired( 'ValidCertSheet' );
} else {
	$sheet    = getRequired( 'ViewCertSheet' );
}
my $page  = $query->getFile ( "$sheet" );
my $cert  = $db->getItem( DATATYPE=>$dataType, KEY=>$key );

configError( i18nGettext ("Error __ERRNO__, unable to get cert from dB! (__ERRVAL__)",
                          "__ERRNO__", $db->errno(),
                          "__ERRVAL__", $db->errval())) if( not $cert );
configError( i18nGettext ("Error, unable load __SHEET__!", "__SHEET__", $sheet)) if( $page eq "" );

push( @cols, gettext("Variable") );
push( @cols, gettext("Value") );

my $parsedCert = $cert->getParsed();

my $certTable = "";
if ( $server =~ /^(CA|RA|LDAP)$/i ) {
	$certTable .= "<form method=\"POST\">\n";
	$certTable .= "<input type=hidden name=\"cmd\" value=\"\">";
	$certTable .= "<input type=hidden name=\"passwd\" value=\"\">";
	$certTable .= "<input type=hidden name=\"key\" value=\"$key\">";
	$certTable .= "<input type=hidden name=\"dataType\" value=\"$dataType\">";
	$certTable .= "<input type=hidden name=\"passwd_dialog_mode\" value=\"user\">";
	$certTable .= "<input type=hidden name=\"dn\" value=\"".$parsedCert->{DN}."\">";
	$certTable .= "<input type=hidden name=\"new_dn\" value=\"\">";
}
$certTable .= $query->startTable( COLS=>[ @cols ], WIDTH=>"100%",
						   BGCOLOR=>"#EEEEF1",
						   TITLE_BGCOLOR=>"#DDCCFF" );

my $tmpIssuer = $parsedCert->{ISSUER};
my $tmpDN     = $parsedCert->{DN};
my $tmpStatus = $status;

## old version - if it can be removed then simply remove it
## $tmpIssuer =~ s/\//<BR>\n/g;
## $tmpDN =~ s/\//<BR>\n/g;
$tmpIssuer =~ s/\,\s*/<BR>\n/g;
$tmpDN =~ s/\,\s*/<BR>\n/g;

$date = $tools->getDate();
if ( $tmpStatus =~ /^Valid/i ) {
	if ($cryptoShell->getNumericDate ($date) >
	    $cryptoShell->getNumericDate ($parsedCert->{NOTAFTER})) {
		$tmpStatus = "<FONT COLOR=\"RED\">".gettext("Expired")."</FONT>";
	}
} elsif ( $tmpStatus =~ /revoked/gi ) {
	$tmpStatus = i18nGettext ("Revoked on __DATE__", "__DATE__", $parsedCert->{HEADER}->{REVOKED});
} elsif ( $tmpStatus =~ /^Expired/i ) {
	if ($cryptoShell->getNumericDate ($date) <=
	    $cryptoShell->getNumericDate ($parsedCert->{NOTAFTER})) {
		$tmpStatus = "<FONT COLOR=\"RED\">".gettext("Not Expired")."</FONT>";
	}
}

$download = $query->url (-full=>1);

##// remove original scriptname to help IE which doesn't know crypto-MIME-types
$download =~ s/\/[^\/]$//;

$download .= '/download.cer?cmd=send_email_cert;type=email;key='.$cert->getSerial();
$revoke   = $query->url (-full=>1).'?cmd=revoke_req;key='.$cert->getSerial();

$certTable .=$query->addTableLine(DATA=>["<B>".gettext("Certificate Version:")."</B>",
                                ($parsedCert->{VERSION} or gettext("n/a")) ]);
$certTable .=$query->addTableLine(DATA=>[ "<B>".gettext("Serial Number:")."</B>",
                                $cert->getSerial() ]);
$certTable .=$query->addTableLine(DATA=>[ "<B>".gettext("Common Name:")."</B>",
                                ($parsedCert->{DN_HASH}->{CN}[0] or gettext("n/a")) ]);
$certTable .=$query->addTableLine(DATA=>[ "<B>".gettext("E-Mail:")."</B>",
                                ($parsedCert->{EMAILADDRESS} or gettext("n/a")) ]);
$certTable .=$query->addTableLine(DATA=>[ "<B>".gettext("Distinguished Name:")."</B>",
                                ($tmpDN or gettext("n/a")) ]);
$certTable .=$query->addTableLine(DATA=>[ "<B>".gettext("Role:")."</B>",
                                ($parsedCert->{HEADER}->{ROLE} or gettext("n/a")) ]);
$certTable .=$query->addTableLine(DATA=>[ "<B>".gettext("Fingerprint:")."</B>",
                                ($parsedCert->{FINGERPRINT} or gettext("n/a")) ]);
$certTable .=$query->addTableLine(DATA=>[ "<B>".gettext("Issued by:")."</B>",
                                ($tmpIssuer or gettext("n/a")) ]);
$certTable .=$query->addTableLine(DATA=>[ "<B>".gettext("Valid From:")."</B>",
                                ($parsedCert->{NOTBEFORE} or gettext("n/a")) ]);
$certTable .=$query->addTableLine(DATA=>[ "<B>".gettext("Expiration on:")."</B>",
                                ($parsedCert->{NOTAFTER} or gettext("n/a")) ]);
$certTable .=$query->addTableLine(DATA=>[ "<B>".gettext("Current Status:")."</B>",
                                ($tmpStatus or gettext("n/a")) ]);

## perhaps an operator want to have a look at the request
if ($parsedCert->{HEADER}->{CSR_SERIAL} and ($server =~ /^(CA|RA)$/i)) {
	my $csr_link .= "<a href=".$query->url(-full=>1).
                        "?cmd=viewCSR&dataType=ARCHIVED_REQUEST&key=".
                        $parsedCert->{HEADER}->{CSR_SERIAL}.">".
                        "$parsedCert->{HEADER}->{CSR_SERIAL}</a>";
	$certTable .= $query->addTableLine(DATA=>[ "<B>".gettext("CSR's Serial Number:")."</B>",
			($csr_link or gettext("n/a")) ]);
}

## show extensions
$certTable .=$query->addTableLine(DATA=>[ "<FONT COLOR=#00FF00><B>".gettext("Extensions:")."</B></FONT>" ]);
foreach my $h (sort keys %{$parsedCert->{OPENSSL_EXTENSIONS}}) {
	my $value = "";
	foreach my $hh (@{$parsedCert->{OPENSSL_EXTENSIONS}->{$h}}) {
		$value .= "\n" if ($value);
		$value .= $hh;
	}
	$certTable .=$query->addTableLine(DATA=>[ "<FONT COLOR=#0000FF><B>$h:</B></FONT>", $value ]);
}

my $special_ops = 0;
## prepare download of private keys
if ($parsedCert->{KEY} and ($server =~ /^(CA|RA)$/i)) {
	if (not $special_ops) {
		$certTable .=$query->addTableLine(DATA=>[ "<FONT COLOR=#00FF00><B>".gettext("Operations:")."</B></FONT>" ]);
		$special_ops = 1;
	}
	my $select = "<select name=\"format\">\n".
			"<option value=\"openssl\">SSLeay (mod_ssl)</option>\n".
			"<option value=\"pkcs8\">PKCS#8</option>\n".
			"<option value=\"pkcs12\">PKCS#12</option>\n".
			"</select>\n";
	my $button = "<input ".
			"TYPE=\"Button\" ".
			"Name=\"Submit\" ".
			"Value=\"".gettext("Download")."\" ".
			"onClick=\"getParams ('send_cert_key', this.form)\">";
	$certTable .= $query->addTableLine(DATA=>[ "<B>".gettext("Certificate and Keypair:")."</B>",
			$select.$button ]);
	## Change passphrase
	my $change_button = "<input ".
                        "TYPE=\"Submit\" ".
                        "Name=\"Submit\" ".
                        "Value=\"".gettext("Change")."\" ".
                        "onClick=\"cmd.value='changePasswd'\">";
	$certTable .= $query->addTableLine(DATA=>[ "<B>".gettext("Change Passphrase:")."</B>",
			($change_button or gettext("n/a")) ]);
	## Remove private key from DB
	my $remove_button = "<input ".
                        "TYPE=\"Submit\" ".
                        "Name=\"Submit\" ".
                        "Value=\"".gettext("Remove")."\" ".
                        "onClick=\"cmd.value='removeKey'\">";
	$certTable .= $query->addTableLine(DATA=>[ "<B>".gettext("Remove Key from database:")."</B>",
			($remove_button or gettext("n/a")) ]);
}

## prepare the actualization of the LDAP
if (($server =~ /^(LDAP)$/i) and (getRequired ('LDAP') =~ /y/i)) {
	if (not $special_ops) {
		$certTable .=$query->addTableLine(DATA=>[ "<FONT COLOR=#00FF00><B>".gettext("Operations:")."</B></FONT>" ]);
		$special_ops = 1;
	}
	## update cert on LDAP
	my $ldap_button = "<input ".
                        "TYPE=\"Submit\" ".
                        "Name=\"Submit\" ".
                        "Value=\"".gettext("Add to LDAP")."\" ".
                        "onClick=\"cmd.value='addCertToLDAP'\">";
	$certTable .= $query->addTableLine(DATA=>[ "<B>".gettext("Add the certificate to LDAP:")."</B>",
			($ldap_button or gettext("n/a")) ]);
	## update cert on LDAP with modified DN
	my $ldap_button = "<input ".
                        "TYPE=\"Button\" ".
                        "Name=\"Submit\" ".
                        "Value=\"".gettext("Add to LDAP with modified DN")."\" ".
                        "onClick=\"getParams( 'addCertToLDAPbyName', this.form ); return false\">";
	$certTable .= $query->addTableLine(DATA=>[ "<B>".gettext("Add the certificate to LDAP but with changed DN:")."</B>",
			($ldap_button or gettext("n/a")) ]);
	## delete cert from LDAP
	my $ldap_button = "<input ".
                        "TYPE=\"Submit\" ".
                        "Name=\"Submit\" ".
                        "Value=\"".gettext("Delete from LDAP")."\" ".
                        "onClick=\"cmd.value='deleteCertFromLDAP'\">";
	$certTable .= $query->addTableLine(DATA=>[ "<B>".gettext("Delete the certificate from LDAP:")."</B>",
			($ldap_button or gettext("n/a")) ]);
	## delete cert from LDAP with modified DN
	my $ldap_button = "<input ".
                        "TYPE=\"Button\" ".
                        "Name=\"Submit\" ".
                        "Value=\"".gettext("Delete from LDAP with modified DN")."\" ".
                        "onClick=\"getParams( 'deleteCertFromLDAPbyName', this.form ); return false\">";
	$certTable .= $query->addTableLine(DATA=>[ "<B>".gettext("Delete the certificate from LDAP but with changed DN:")."</B>",
			($ldap_button or gettext("n/a")) ]);
}
if (($server =~ /^(CA|RA)$/i) and
    not $parsedCert->{IS_CA} and
    $status ne gettext("Revoked") and
    $status ne gettext("Suspended")
   )
{
	if (not $special_ops) {
		$certTable .=$query->addTableLine(DATA=>[ "<FONT COLOR=#00FF00><B>".gettext("Operations:")."</B></FONT>" ]);
		$special_ops = 1;
	}
	my $ra_button = "<input ".
                        "TYPE=\"Submit\" ".
                        "Name=\"Submit\" ".
                        "Value=\"".gettext("Download certificate onto token")."\" ".
                        "onClick=\"cmd.value='getcert'\">";
	$certTable .= $query->addTableLine(DATA=>[ "<B>".gettext("Tokenhandling:")."</B>",
			($ra_button or gettext("n/a")) ]);
}
if ($server =~ /^(RA)$/i) {
	if (not $special_ops) {
		$certTable .=$query->addTableLine(DATA=>[ "<FONT COLOR=#00FF00><B>".gettext("Operations:")."</B></FONT>" ]);
		$special_ops = 1;
	}
	my $ra_button = "<input ".
                        "TYPE=\"Submit\" ".
                        "Name=\"Submit\" ".
                        "Value=\"".gettext("Write a mail")."\" ".
                        "onClick=\"cmd.value='writeCertMail'\">";
	$certTable .= $query->addTableLine(DATA=>[ "<B>".gettext("Send mail to the User:")."</B>",
			($ra_button or gettext("n/a")) ]);
}
if ($server =~ /^(RA)$/i and $status ne gettext("Revoked"))
{
	if (not $special_ops)
	{
		$certTable .=$query->addTableLine(DATA=>[ "<FONT COLOR=#00FF00><B>".gettext("Operations:")."</B></FONT>" ]);
		$special_ops = 1;
	}
	my $ra_button = "<input ".
                        "TYPE=\"Submit\" ".
                        "Name=\"Submit\" ".
                        "Value=\"".gettext("Revoke")."\" ".
                        "onClick=\"cmd.value='revoke_req'\">";
	$certTable .= $query->addTableLine(DATA=>[ "<B>".gettext("Start Revocation:")."</B>",
			($ra_button or gettext("n/a")) ]);
}

$certTable .= $query->endTable();
if ( $server =~ /^(CA|RA|LDAP)$/i ) {
	$certTable .= "</form>\n";
} else {
	if ($dataType =~ /(VALID|EXPIRED|SUSPENDED)_CERTIFICATE/) {
		$certTable .= "<center><b>\n".
			"<a href=\"".$download."\">".gettext("Download the certificate")."</a>\n".
			"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n".
			"<a href=\"".$revoke."\">".gettext("Revoke the certificate")."</a>\n".
			"</b><br><br></center>\n";
	}
}
$certTable .= getCopyRight();

$page = $query->subVar( $page, '$serial',   $cert->getSerial() );
$page = $query->subVar( $page, '$certable', $certTable );
$page = $query->subVar( $page, '$key',      $key );
$page = $query->subVar( $page, '$dataType', $dataType );

print "$page";

}
1;
