## OpenCA - Command
## (c) 1998-2001 by Massimiliano Pala and OpenCA Group
##
##   File Name: lists
##       Brief: lists objects
## Description: lists requests and certificates
##  Parameters: action (type of list)

sub cmdLists {

my $action = $query->param('action');

if ( "$action" eq "" ) {
        configError(gettext("Command Error (Command Missing)"));
}


## Variables Definition
my $getID_url = 'pki?cmd=viewCert;';

my $from    = ( $query->param( 'viewFrom' ) or 0 );
my $matched = $query->param( 'rows' );

## Set the column titles
my ( $dbItem, $listType, @list, @cols, $newCMD );

## Differentiate the list parameters
if( $action =~ /^certsList/i) {
	$dataType  = 'VALID_CERTIFICATE';
	$listType  = gettext('<FONT COLOR="#FF7000">V</FONT>alid <FONT COLOR="#FF7000">C</FONT>ertificates');

	$newCMD    = $getID_url;

	push( @cols, gettext("Serial") );
	push( @cols, gettext("Common Name") );
	push( @cols, gettext("Issued on") );
	push( @cols, gettext("E-Mail") );
	push( @cols, gettext("Role") );

} elsif( $action =~ /^certsExpiredList/i) {
	$dataType  = 'EXPIRED_CERTIFICATE';
	$listType  = gettext('<FONT COLOR="#FF7000">E</FONT>xpired <FONT COLOR="#FF7000">C</FONT>ertificates');

	$newCMD    = $getID_url;

	push( @cols, gettext("Serial") );
	push( @cols, gettext("Common Name") );
	push( @cols, gettext("Issued on") );
	push( @cols, gettext("E-Mail") );
	push( @cols, gettext("Role") );

} elsif( $action =~ /^pendingReqs/i) {
	$dataType  = 'PENDING_REQUEST';
	$listType  = gettext('<FONT COLOR="#FF7000">P</FONT>ending <FONT COLOR="#FF7000">R</FONT>equests');

	push( @cols, gettext("Serial") );
	push( @cols, gettext("Requested By") );
	push( @cols, gettext("Requested on") );
	push( @cols, gettext("Requested Role") );

} elsif ( $action =~ /^revokedList/i ) {
	$dataType  = 'REVOKED_CERTIFICATE';
	$listType  = gettext('<FONT COLOR="#FF7000">R</FONT>evoked <FONT COLOR="#FF7000">C</FONT>ertificates');

	$newCMD    = $getID_url;

	push( @cols, gettext("Serial") );
	push( @cols, gettext("Common Name") );
	push( @cols, gettext("Revoked On") );
	push( @cols, gettext("E-Mail") );
	push( @cols, gettext("Role") );

} elsif ( $action =~ /^suspendedList/i ) {
	$dataType  = 'SUSPENDED_CERTIFICATE';
	$listType  = gettext('<FONT COLOR="#FF7000">S</FONT>uspended <FONT COLOR="#FF7000">C</FONT>ertificates');

	$newCMD    = $getID_url;

	push( @cols, gettext("Serial") );
	push( @cols, gettext("Common Name") );
	push( @cols, gettext("Suspended On") );
	push( @cols, gettext("E-Mail") );
	push( @cols, gettext("Role") );

} elsif( $action =~ /^pendingCrrs/i) {
	$dataType  = 'PENDING_CRR';
	$listType  = gettext('<FONT COLOR="#FF7000">P</FONT>ending <FONT COLOR="#FF7000">R</FONT>equests');

	push( @cols, gettext("Serial") );
	push( @cols, gettext("Requested By") );
	push( @cols, gettext("Requested on") );
	push( @cols, gettext("Affected Role") );

} else {
	configError(gettext("Requested List NOT available"));
}

## Get required parameters ( return only the value string )
my $sheet    	= getRequired( 'PendingList' );
my $maxItems 	= getRequired( "maxReturnedItems" );

## Get the base Page ( got in $page variable )
my $page 	= $query->getFile( "$sheet" );
my $uptime 	= $tools->getDate();

configError ( i18nGettext ("Error loading Page __PAGE__!", "__PAGE__", $sheet) ) if ( not $page);

if ( not $matched ) {
	$matched  = $db->elements( DATATYPE=>$dataType );
};

@list = $db->listItems( DATATYPE=>$dataType, FROM=>$from, ITEMS=>$maxItems );

$table  = $query->buildRefs( ELEMENTS=>$matched, ITEMS=>$maxItems, FACTOR=>5, MODE=>"EXP" );

if (not @list) {
	$table = $query->buildRefs(
			ELEMENTS  => $matched,
			MAXITEMS  => $maxItems,
			FACTOR    => 5,
			MODE      => "EXP",
			NOW_FIRST => 0,
			NOW_LAST  => 0,
			FIRST     => 0,
			LAST      => 0);
} else {
	$table = $query->buildRefs(
			ELEMENTS  => $matched,
			MAXITEMS  => $maxItems,
			FACTOR    => 5,
			MODE      => "EXP",
			NOW_FIRST => $list[0]->getSerial($dataType),
			NOW_LAST  => $list[scalar (@list) -1]->getSerial($dataType),
			FIRST     => libDBGetFirstItem ($dataType)->getSerial($dataType),
			LAST      => libDBGetLastItem ($dataType)->getSerial($dataType));
}

$table .= $query->startTable( COLS=>[ @cols ],
                              WIDTH=>"100%",
                              TITLE_BGCOLOR=>"#DDCCFF" );

## Process all Files
foreach $dbItem ( @list ) {

	## Common Variables
	my ( $format, $key, $ser_col, $op_col, $email, $email_col, $role_col );
	my ( $lnk, $parsed, $head );

        my @vals;

	$parsed = $dbItem->getParsed();
	$head	= $parsed->{HEADER};

        $key    = $dbItem->getSerial();
	$submit = $parsed->{DN_HASH}->{CN}[0];

        $notBefore = ( $parsed->{NOTBEFORE} or $head->{NOTBEFORE}
			or $parsed->{SUBMIT_DATE} );

	if( $dataType =~ /CRR/ ) {
		if ($parsed->{SIGNATURE}) {
			## signature-based revocation
			if (my $sig = libGetSignatureObject ( OBJECT => $dbItem )) {
				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: $key)\n";
				}
			} else {
				$submit = gettext("Cannot build object from signature!");
				print STDERR "Cannot build object from signature (CRR: $key)\n";
			}

		} elsif ($parsed->{REVOKE_CERTIFICATE_DN}) {
			## pin-based revocation
			$submit = $parsed->{REVOKE_CERTIFICATE_DN};
		} else {
			## last chance by strong ssl-authentication
			$submit = $parsed->{HEADER}->{SSL_CERT_DN};
			print STDERR "submitter of CRR not determinable (CRR: $key)\n";
		}
	}

	if( $dataType =~ /CERTIFICATE/i ) {
        	$ser_col = "<a href=\"$newCMD&dataType=$dataType" .
                		"&key=$key\">". $key ."</a>";
	} else {
		$ser_col = $key;
	}

        if( (not $head->{OPERATOR}) or ($head->{OPERATOR} eq gettext("n/a")) ) {
                $op_col = gettext("n/a");
        } else {
                my $tmpOp = $head->{OPERATOR};
                $op_col = "<a href=\"$self?cmd=searchCert&dataType=" .
                          "CERTIFICATE&key=$tmpOp\">" .
                           $tmpOp ."</a>";
        }

	if ($dataType =~ /CRR/) {
		my $cert = $db->getItem (
					DATATYPE => "CERTIFICATE",
					KEY => $parsed->{REVOKE_CERTIFICATE_SERIAL} );
		if ($cert) {
			$role_col = $cert->getParsed()->{HEADER}->{ROLE};
		} else {
			$role_col = "<font color=#ff0000>".
				gettext ("Cannot load the affected certificate!")."</font>";
		}
	} else {
		$role_col = $head->{ROLE};
	}

	push( @vals, $ser_col );
        push( @vals, ( $submit or gettext("n/a") ) );
        push( @vals, ( $notBefore or gettext("n/a") ) );

	if( $dataType =~ /CERTIFICATE/ ) {
		if( $parsed->{EMAILADDRESS} ) {
			$email = ( $parsed->{EMAILADDRESS} or gettext("n/a") );
			$lnk = new CGI({
				subject=>i18nGettext ("Certificate Serial __CERT_SERIAL__", "__CERT_SERIAL__", $key)});
			$email_col = $lnk->a({-href=>"mailto:$email"},
							$email );
		} else {
			$email_col = "<CENTER>---</CENTER>";
		};

        	push( @vals, $email_col );
	}
	push( @vals, $role_col );

        $table .= $query->addTableLine( DATA =>[ @vals ]);
}


## Close the Table
$table .= $query->endTable();
$table .= getCopyRight();

## Substitute the Variables in the $page
$page = $query->subVar( $page, '@UPTIME@', $uptime );
$page = $query->subVar( $page, '@TABLE@', $table );
$page = $query->subVar( $page, '@LISTTYPE@', $listType );

print "$page";

}

1;

