#!/usr/local/bin/perl5
#
$| = 1;
#
# wwwgnats.pl - a WWW interface to the GNATS bug tracking system
# Thanks to Larry Wall, CERN, and NCSA for Perl, WWW, and Mosaic!
#
$pathinfo = $ENV{"PATH_INFO"};
@pathlist = split(/\//, $pathinfo);
$prog = shift(@pathlist);
$domain = shift(@pathlist);
$username = shift(@pathlist);
if ($username eq "") {
    $username = "1";
}
$eladdress = shift(@pathlist);
if ($eladdress eq "") {
    $eladdress = "1";
}
$domain =~ s/^/-/;
$path = join("/", @pathlist);
$path2 = join("/","",$username,$eladdress);
 
if ($path eq "") {
    $path = "";
} else {

    $path = ("/".$path);
}

$PATH_INFO = $path;

$SCRIPT_NAME = $ENV{"SCRIPT_NAME"}.$domain.$path2;

require "/nnnn/nnn/www/cgi-bin/libgnats.pl";
require "/nnnn/nnn/www/cgi-bin/cgi-lib.pl";

#### Configuration begins here

# Miscellanous data
$EDITOR_FILE = "$GNATS_ADM/editors".$domain;
$ORIGIN_FILE = $EDITOR_FILE;
#$ORIGIN_FILE = "/etc/mail/ccmail";
# Outside commands
$MAILER      = "/usr/lib/sendmail -oi -t";
$DATEPROG    = "/bin/date";
$LSPROG      = "/bin/ls";
### Configuration ends here

### Environment variables
#$SCRIPT_NAME = $ENV{"SCRIPT_NAME"};
#$PATH_INFO = $ENV{"PATH_INFO"};
$QUERY_STRING = $ENV{"QUERY_STRING"};
$CONTENT_LENGTH = $ENV{"CONTENT_LENGTH"};
$HTTP_AGENT = $ENV{"HTTP_USER_AGENT"};
$SERVER_NAME = $ENV{"SERVER_NAME"};
$REMOTE_HOST = $ENV{"REMOTE_HOST"};
$REMOTE_IDENT = $ENV{"REMOTE_IDENT"};
$REMOTE_ADDR = $ENV{"REMOTE_ADDR"};
#################### Array definitions
# Query-pr's -i option outputs the following fields numerically.
# Define arrays to map numbers to name.
$validcateg = join("|", @nCategory);
### Arrays for quick output display with restricted output fields
@quickSeverity = ("", "critical", "serious", "noncri");
@quickPriority = ("", "High", "Medium", "Low");
@quickfmt    = ("brief","regular","verbose");
   # The first field is the quickfmt, the second is the field width
%field      = (
		"CATEGORY",     "0:10",
		"RELEASE",      "2:10", # Not displayed
		"SEVERITY",     "4:8",  # Not displayed
		"PRIORITY",     "1:8", 
		"RESPONSIBLE",  "1:8",
		"STATE",        "0:8",
		"CLASS",        "2:8",
		"SUBMITTER",    "2:7", # Not displayed
	        "START_DATE",   "1:15",
		"END_DATE",     "2:15",
		"ARRIVAL_DATE", "1:14",
		"ORIGINATOR",   "1:9",
		"SYNOPSIS",     "0:0",
	     );
   # Defines order of field display in quick output
@field      = (
		"CATEGORY",
		"RELEASE",
		"SEVERITY",
		"PRIORITY",
		"RESPONSIBLE",
		"STATE",
		"CLASS",
	        "START_DATE",
                "END_DATE",
		"SUBMITTER",
		"ARRIVAL_DATE",
		"ORIGINATOR",
		"SYNOPSIS",
	     );

### Arrays for quick output of PR's with restricted characteristics
   # The first field is the restriction, the second field is the default option
%quickrestr = (
                "Category",    "any",
		"State",       "any",
		"Responsible", "any",
		"Originator",  "any",
	    );
   # Defines order of quick output restrictions, originally was also 
# the Originator field
@quickrestr = (
                "Category",
		"State",
		"Responsible",
	    );

# month array for change_date procedure
%montharray = (
	       "Jan", 1,
	       "Feb", 2,
	       "Mar", 3,
	       "Apr", 4,
	       "May", 5,
	       "Jun", 6,
	       "Jul", 7,
	       "Aug", 8,
	       "Sep", 9,
	       "Oct", 10,
	       "Nov", 11,
	       "Dec", 12,
	        1, "Jan",
	        2, "Feb",
	        3, "Mar", 
	        4, "Apr",
	        5, "May",
	        6, "Jun",
	        7, "Jul",
	        8, "Aug",
	        9, "Sep",
	        10, "Oct",
	        11, "Nov",
	        12, "Dec",
	       );


#################### Main routine
# Main Program
print "Content-type: text/html\n\n";
print "<HTML>\n";

&read_originator;
&read_editor;

### Submit a new PR
if ($PATH_INFO =~ m,^/send_pr,) {
    &send_pr();
} elsif ($PATH_INFO =~ m,^/handle_send_pr,) {
    &handle_send_pr();

### Edit an existing PR

} elsif ($PATH_INFO =~ m,^/handle_edit_pr/,) {
    if ($PATH_INFO =~ m,^/handle_edit_pr/(\d+)&([^&]+)&([^&]+)$,) {
	&handle_edit_pr($1, $2, $3);
    } else {
	print "Bad args for handle_edit_pr!\n";
	print "Args are $PATH_INFO.\n";
	if ($PATH_INFO =~ m,^/handle_edit_pr/(\d+)&,) {
	    print "Doesn't have digits&\n";
	}
	if ($PATH_INFO =~ m,^/handle_edit_pr/(\d+)&([^&]+)&,) {
	    print "Doesn't have digits&stuff\n";
	}
    }

### Display the entire PR
} elsif ($PATH_INFO =~ m,^/full,) {
    local($subdir);
    $subdir = $PATH_INFO;
    if ($subdir =~ m,^/full/(\d+),) {  # Called from quick query
        &query_full($1);
    } else {
	$QUERY_STRING =~ m,^pr=(\w+)$,;
	&query_full($1);
    }

### Query a number of PR's and display in quick output form
} elsif ($PATH_INFO =~ m,^/quick,) {
    # Get arg of quickfmt=
    $QUERY_STRING =~ m,^quickfmt=(\w+)&.*&Date=([^&]*)&,;
    $QUICKFMT = $1;
    $DATEVALUE=$2;
    if ($DATEVALUE eq "last+week") {
        $do_listing=1;
    }    
    if ($QUERY_STRING =~ m,date_start=([^&]*)&date_end=(.*),) {
	$DATEVALUE="manual+input+done";
	$do_listing=1;
	$DATESTART=$1;
	$DATEEND=$2;
	$QUERY_STRING =~ s/date_start=([^&]*)&date_end=(.*)//;
    }
    &change_date;
    $QUERY_STRING =~ s/&Date=([^&]*)&/&Date=$DATEVALUE&/;
    # Get all restrictions.  First, strip off quickfmt prefix.
    ($RESTR = $QUERY_STRING) =~ s/^quickfmt=\w+&//;
    # Then, split into words.
    @RESTR=split(/&/,$RESTR);
    &query_quick($QUICKFMT,@RESTR);

### Get count of pending bugs by category
} elsif ($PATH_INFO =~ m,^/summary_cat,) {

    &query_summary_cat();

### Get count of pending bugs by person
} elsif ($PATH_INFO =~ m,^/summary,) {

    &query_summary();
### Get custom summary
} elsif ($PATH_INFO =~ m,^/custom_sum,) {

    &custom_sum();

### Report generation
} elsif ($PATH_INFO =~ m,^/report,) {

    &report();

### Main menu
} elsif ($PATH_INFO eq "") {
    &main_menu();
    print"<HR>\n";
    #print"<HR>Original Version: 15 Mar 95<BR>Authors: <A HREF=\"http://alumni.caltech.edu/~dank\">Dan Kegel</A> (dank\@alumni.caltech.edu) & Huy Le (huyle\@alumni.caltech.edu)\n";

  
} else {
    print "<head><title>SPR Front End</title></head>
<H1>SPR Front End</H1>
<body>
";
   print "Bad subdirectory/parameters specified in URL.\n";
}


print "\n</body>\n";
print "</HTML>\n";
exit(0);


#################### PR submission

# Sends the new PR
sub handle_send_pr {   
    # Display title
#    print &PrintHeader();
    print "<head><title>New Problem Report submission</title></head>
<body>
";
   
    # Get arguments
    local($_)=scalar(<STDIN>);
    chop; s/\r$//;
    local($i,%input);
    undef(%fieldvalues);	# Global!
    foreach (split(/&/)) {
        ++$i;
        local($key,$value)=split(/=/);
	$value = &cgi_trans($value);
	# By convention, multi-line fields have newlines at end of
	# each line.  I think some browsers forget the last newline?
	if ($fieldnames_multi{$key} > 0 && $value !~ /\n$/) {
	    $value .= "\n"; 
	    
	}
       
       # $fieldvalues{$key}=$value;
	#parche
	if ($fieldnames_multi{$key} > 0) {
	  #  print "<h3>He cogido un campo a formatear</h3>";
	    &format_sixty($value);
	  #  print"<h3>"; print $value; print"</h3>";
	}
	#fin parche
	$fieldvalues{$key}=$value;
    }

    # Verify arguments
    local($field);
    foreach $field ("Originator", "Category", "Release", "Synopsis", "Environment", "Description" ) {
	if ($fieldvalues{$field} eq "") {
	    print "<H3>Your problem report has not been sent.</H3>\n";
	    print "You must select/fill  $field.\n";
	    return;
	}
       
    }

    # kludge
    $fieldvalues{"Confidential"} = "no";
    # megakludge.
    $fieldvalues{"Submitter-Id"} = $fieldvalues{"Organization"};
    if ($fieldvalues{"Organization"} eq "CERN") {
	$fieldvalues{"Submitter-Id"} = "cern.ch";
	 }
    # Send the PR
    $prtext = &unparse_pr("send");
   
    open(MAIL, "|$MAILER") || die "Error while invoking sendmail";
#    print MAIL
#"To: $GNATS_ADDR
#Subject:wwwgnats.pl
#From: $nOriginator{$fieldvalues{\"Originator\"}} ($fieldvalues{\"Originator\"})
#Reply-To: $nOriginator{$Originator}
#X-send-pr-version: $GNATS_VER
# changes for the new field Originator and Name
   print MAIL
"To: $GNATS_ADDR
Subject:$fieldvalues{\"Synopsis\"}
From: $fieldvalues{\"Email\"} ($fieldvalues{\"Originator\"})
Reply-To:$fieldvalues{\"Email\"}
X-send-pr-version: $GNATS_VER

$prtext";
    close(MAIL);
    print "<H3>Your problem report has been sent.  It will take about 10 minutes to show up in the system.</H3>\n";
    
}
1;



####################################
# Sends the PR changes
sub handle_edit_pr  {
    # Display title
#    print "<head><title>Problem Report editing</title></head>
#<body>
#";
    # Initialization
    $errmsg="<H3>Your problem report changes have not been sent.</H3>\n";

    # Get the PR, editor, old state, and timestamp
    local($pr, $oldstate, $timestamp) = @_;

    # Get arguments
    local($_)=scalar(<STDIN>);
   
  
    chop; s/\r$//;
    local($i,%input);
    foreach (split(/&/)) {
        ++$i;
        local($key,$value)=split(/=/);
        $input{$key}=&cgi_trans($value);
       
    
    #in multiline fields get append newline at the end, for response and how-to-repeat
    # By convention, multi-line fields have newlines at end of
	# each line.  I think some browsers forget the last newline?
	if ($fieldnames_multi{$key} > 0 && $value !~ /\n$/) {
	    $input{$key} .= "\n";
	}

#parche
	if ($fieldnames_multi{$key}>0) {
	    &format_sixty($input{$key});
	}
#end of parche

    # end of newline append
   } 
    # Verify arguments
 #   if (!$input{"Editor"}) {
 #      print $errmsg, "You must register your name.\n";
 #	return;
 #   }
     
    if (!$nEditor{$input{'Editor'}}) {
    print "<head><title>Problem Report editing</title></head>
<body>
";
      
	print $errmsg, "You're not registered as editor.\n";
 	return;
    }
    # Lock and read the PR into @oldpr and %fieldvalues\"submit\"
    # Also sets $semipr and $fullpr
    $err = &read_pr($pr, $input{"Editor"});
    if ($err ne "") {
	print $errmsg, $err;
	return;
    }
    #local($oldstate) = $fieldvalues{"State"};
    local($oldsyn) = $fieldvalues{"Synopsis"};
    local($oldresp) = $fieldvalues{"Responsible"};
    local($startdate) = $fieldvalues{"Start-Date"};
    local($enddate) = $fieldvalues{"End-Date"};
   # Kludge to allow editing of Response and How-To-Repeat fileds
    local($oldfix) =  $fieldvalues{"Response"};
    local($oldhowtorepeat) = $fieldvalues{"How-To-Repeat"};
    # end of kludge
#
    $oldresp =~ s/\s*\(.*$//; # Get rid of comment in responsible party name
    local($reply_to) = $fieldvalues{"Reply-To"};
    if ($reply_to eq "") {
	# "Reply-To:" takes precedence over "From:".
	$reply_to = $fieldvalues{"From"};
    }

    local($ed_err);
    local(%mail_to);
    local($change_msg) = "***********************************************\n";
    LOCKED: {
	# Now that pr has been locked, if any errors are encountered,
	# set $ed_err to the reason and jump to UNLOCK.

	# Check that the timestamp hasn't changed since the form was generated
	if ($timestamp ne &timestamp($fullpr)) {
	    $ed_err = "$errmsg\nThis PR has been modified since you started editing it.\n";
	    last LOCKED;
	}

	# Another sanity check
	if ($reply_to eq "" || $oldresp eq "") {
	    $ed_err = "$errmsg\nHey!  Old responsible is '$oldresp', reply address on pr is '$reply_to'!\n";
	    last LOCKED;
	}

	# Get the date
	local($date);
	if (!open(DATE, "$DATEPROG|")) {
	    $ed_err = "$errmsg\nError: can't run $DATEPROG";
	    last LOCKED;
	}
	chop($date=<DATE>);
	close(DATE);

	$mail_to{&tolower($nEditor{$input{'Editor'}})} = 1;
	local($to_subm, $to_old, $to_new);
	$responsible = $input{'Responsible'};
		$resp_fullname = &read_resp_fullname($responsible);

	# Update the audit trail
	#print "if ($input{'State'} ne $fieldvalues{'State'})\n";
	if ($input{"State"} ne $fieldvalues{'State'}) {
	   
# if status changes from open to assigned but the resp is the same 
# notify it to the user
	    if ($input{'State'} eq "assigned" && $fieldvalues{'State'} eq "open") {
       	if ($input{'StateReason'} eq "") {
		$input{'StateReason'} .= "The responsible assigned  is  $resp_fullname";
	    }
    }
# end of test    

## Next lines commented. Reason for change of state no longer required.
		
#	    if ($input{'StateReason'} eq "") {
#
#		$ed_err = "$errmsg\nYou must give the reason for the State change.\n";
#		last LOCKED;
#	    }
	    $change_msg .= "State-Changed-From-To: $fieldvalues{'State'}-$input{'State'}
State-Changed-By: $input{'Editor'}
State-Changed-When: $date
State-Changed-Why: $input{'StateReason'}    
";
	    $to_subm = 1;
	    $fieldvalues{'State'} = $input{'State'};
	}

	if ($input{'Responsible'} ne $oldresp) {
	    if ($input{'ResponsibleReason'} eq "") {
		$ed_err = "$errmsg\nYou must tell why the Responsible person changed.\n";
		last LOCKED;
	    }
# Kludge if status changed from open to assigned & resp is assigned then notify
	    if ($input{'State'} eq "assigned" && $oldstate eq "open") {
		$change_msg .= "Responsible-Assigned: $resp_fullname\n";
	    }
	    else {
		$change_msg .= "Responsible-Changed-From-To: $fieldvalues{'Responsible'}-$input{'Responsible'} ($resp_fullname)\n";
	    }
	    
$change_msg .= "Responsible-Changed-By: $input{'Editor'}
Responsible-Changed-When: $date
";
# end of kludge
	   $to_subm = $to_old = $to_new = 1;
	    $fieldvalues{'Responsible'} = $input{'Responsible'}." (".$resp_fullname.")";
	}


#my little kludge: first I check if a category from other domain has been
#chosen
    open(DOMAIN, "$GNATS_ADM/domains") ||
	die "Couln't get domains file\n";
    while (<DOMAIN>) {
	if (!/^\s*#|^\s*\n$/) {
	    $_ =~ s/^/-/;
	    push(@nDomain, $_);
	}
    }
    close(DOMAIN);
    @nDomain = sort(@nDomain);
#    unshift(@nCategory, "");  # needed for 'any'
   
	$modified=0;
	$i=1;
	$chdomain=0;
	foreach $domi (@nDomain) {
	    if ($i>0) { chop ($domi);}
	    $i++;
	$estrin="Category".$domi;
#	print "<h1>$estrin</h1>";
	    if ($input{$estrin}) {
		$modified++;
		$newdomain=$domi;
		#in newdomain I keep the new domain of the pr, it will only
		#be valuable if only 1 domain has been chosen (error otherwise)
	    }
#	print"<h4>lala$input{$estrin}</h4>";
	}
	if ($modified>1) {
	    print "<h1>Error! You've moved the pr to more than 1 domain !</h1>";
	    system("$PR_EDIT --unlock $semipr");
	    print "</HTML>";
	    exit(0);
	}
	if ($modified>0) {
	    $oldomain=$domain;    # We keep the old domain 
	    $oldomain=~ s/^-//;   # Remove the dash
	    $domain = $newdomain; # Replace domain with the new value
	    $newdomain =~ s/^-//; # Remove the dash . Jesus 6/12/96.
	    print "<h1>You've moved the report to domain $newdomain</h1>";
	    $estrin="Category".$domain;
	    #$chdomain=1; # we don't need this value anymore, we're not
			  # going to re-submit the problem report. Jesus 6/12/96
	    #this variable will act as boolean to check if there has been a
	    #change of domain
	    $input{"Category"}=$input{$estrin};
	    print "<h2>New category: $input{$estrin}</h2>";
	    # The problem is not marked as moved, we just change the category.
	    # Jesus 6/12/96.
#	    print "<p>This problem report has be marked as <em>moved</em> and submitted to the new responsibles</p>";
	    

	    $change_msg.="Domain changed from: $oldomain to: $newdomain\n";

	    # This lines were from older versions in which we changed the state.
	    # Jesus 6/12/96.
#	    $input{'StateReason'}="The problem report has been moved to another domain";
	    #$change_msg.="State changed from: $fieldvalues{\"State\"} to: moved
#	    $change_msg.="State-Changed-By: $input{'Editor'}
#State-Changed-When: $date
#State-Changed-Why:
#$input{'StateReason'}
#";
	    #$fieldvalues{"State"}="moved";
	}
#
      
#end of my little kludge, but in fact this if which comes next should be 
#executed only if there hasn't been a change of domain.


	if ($input{"Category"} ne $fieldvalues{"Category"}) {
	    # Gnats' original edit-pr command didn't generate an audit
	    # trail for this change
	    # Note: category names might have dashes in them, making
	    # the following line hard to parse!

# if the category is changed then the responsible should be reassigned

open(CATEG, "$GNATS_ADM/categories".$domain) ||
	die "Couln't get categories file\n";
    while (<CATEG>) {
	if (!/^\s*#|^\s*\n$/) {
	    chop;	
    @nResp = split(/:/, $_);
	    $cat=shift(@nResp);
	    $descr=shift(@nResp);
	    $a=@nResp;
#	    print " responsibles @nResp length $a\n";
	    if ($cat eq $input{'Category'} ) {
		$fieldvalues{'Responsible'} = shift(@nResp);
		$nresponsible = $fieldvalues{'Responsible'};
		$nresp_fullname = &read_resp_fullname($nresponsible);
				
	    }
	
	}

    }




	    $change_msg .= 
"Category-Changed-From: $fieldvalues{'Category'} To: $input{'Category'}
Category-Changed-By: $input{'Editor'}
Category-Changed-When: $date
\n";

$change_msg .= "Responsible-Changed-From-To: $input{'Responsible'} ($resp_fullname) - $fieldvalues{'Responsible'} ($nresp_fullname)\n";    
$change_msg .= "Responsible-Changed-By: $input{'Editor'}
Responsible-Changed-When: $date
";
if ($modified>0) {  # The reason of the Responsible change could be due to a
		    # change in the domain... Jesus 6/12/96.
$change_msg .= "Responsible-Changed-Why: Due to change in domain from $oldomain to $newdomain
";}
else {		    # ... or a change in the category. Jesus 6/12/96.
$change_msg .= "Responsible-Changed-Why: Due to change in category from $fieldvalues{'Category'} to $input{'Category'}
";}

	    $fieldvalues{'Category'} = $input{'Category'};
            $input{'Responsible'} = $fieldvalues{'Responsible'};
	     $fieldvalues{'Responsible'} .= " (".$nresp_fullname.")";
		$to_subm = $to_old = $to_new = 1;
}


#### Update the start-date and end-date fields if they have changed

if ($input{"Start-Date"} ne $fieldvalues{'Start-Date'}) {
	       
	    $change_msg .= "Start-Date-Changed-From-To: $fieldvalues{'Start-Date'}-$input{'Start-Date'}
State-Changed-By: $input{'Editor'}
State-Changed-When: $date
";
	    #$to_subm = 1;
	    $fieldvalues{'Start-Date'} = $input{'Start-Date'};
	}



if ($input{"End-Date"} ne $fieldvalues{'End-Date'}) {
	       
	    $change_msg .= "End-Date-Changed-From-To: $fieldvalues{'End-Date'}-$input{'End-Date'}
State-Changed-By: $input{'Editor'}
State-Changed-When: $date
";
	    #$to_subm = 1;
	    $fieldvalues{'End-Date'} = $input{'End-Date'};
	}


      # Update the audit trail if Response and How-To-Repeat fields have changed

#en la buena la siguiente linea no eta en comentario
#aparte anyado los chops para quitar la paja al final \n's y  \r's
      #	$oldfix=chop($oldfix);

	while (($input{"Response"}=~/\n$/) || ($input{"Response"}=~/\r$/)){
	    chop($input{"Response"});
	     }

	while (($oldfix=~/\n$/) || ($oldfix=~/\r$/)){
	    chop($oldfix);
	     }
	  
# To avoid the modification of the Response field if it's empty
# in the form submitted. Jesus 14/11/96.

	if (($input{"Response"} ne "")&&($input{"Response"} ne $oldfix)) {
#	if ($input{"Response"} ne $oldfix) {
	    # Gnats' original edit-pr command didn't generate an audit
	    # trail for this change
	    
	if ($oldfix ne "") { # if the Response field had a value,
$change_msg .=               # the old value and the new one will be 
		             # reflected in the audit-trail. Jesus 4/12/96.
"Response-Changed-From:
 $fieldvalues{\"Response\"}
To:
 $input{\"Response\"}
";}
	else {		     # if the Response field was empty
$change_msg .=               # we only reflect the new value in 
			     # the audit-trail. Jesus 4/12/96.
"Response-Changed-To:
 $input{\"Response\"}
";}

$change_msg .=
"Response-Changed-By: $input{'Editor'}
Response-Changed-When: $date
\n";	    
        $input{"Response"} .= "\n";
	$fieldvalues{'Response'} = $input{'Response'};
	$to_subm = 1; # to inform the submitter when the
		      # Response field is changed but there is
		      # no state change. Jesus 14/11/96.
	}

	$input{"Response"} .= "\n";
	$oldfix .= "\n";

      #  same for the How-To-Repeat field

# same as for Response

      #	$oldhowtorepeat=chop($oldhowtorepeat);

	while (($input{"How-To-Repeat"}=~/\n$/) || ($input{"How-To-Repeat"}=~/\n$/)){
	    chop($input{"How-To-Repeat"});
	     }

#	    print "<h1>El input howto chopped: ";
#	    print $input{"How-To-Repeat"};

	while (($oldhowtorepeat=~/\n$/) || ($oldhowtorepeat=~/\n$/)){
	    chop($oldhowtorepeat);
	     }

#	    print $oldhowtorepeat;
#	print "</h1>";
	  
# To avoid the modification of the How-To-Repeat field if it's empty
# in the form submitted. Jesus 4/12/96.
	if (($input{"How-To-Repeat"} ne "")&&($input{"How-To-Repeat"} ne $oldhowtorepeat)) {
	    # Gnats' original edit-pr command didn't generate an audit
	    # trail for this change
	if ($oldhowtorepeat ne "") { # if the How-To-Repeat field had a value,
	    $change_msg .=           # the old value and the new one will be 
			             # reflected in the audit-trail. Jesus 4/12/96.
	    "How-To-Repeat-Changed-From: 
 $fieldvalues{\"How-To-Repeat\"}
To:
 $input{'How-To-Repeat'}
";}
	else {		               # if the How-To-Repeat field was empty
	  $change_msg .=               # we only reflect the new value in 
			               # the audit-trail. Jesus 4/12/96.
	  "How-To-Repeat-Changed-To:
 $input{\"How-To-Repeat\"}
";}
	  $change_msg .=
"How-To-Repeat-Changed-By: $input{'Editor'}
How-To-Repeat-Changed-When: $date
\n";    

	    $input{"How-To-Repeat"}.="\n";
	    $fieldvalues{'How-To-Repeat'} = $input{'How-To-Repeat'};
	 }
	$input{"How-To-Repeat"}.="\n";
      # end of change

	# Check that changes were actually made
	if ($change_msg eq "") {
	    $ed_err = "$errmsg\nNothing was changed.\n";
	    last LOCKED;
	}
	# Add the change log to the PR
	$fieldvalues{'Audit-Trail'} .= $change_msg;

	# Generate the mailing list
	if ($to_subm) {
	    $mail_to{&tolower($reply_to)} = 1;
	}
	if ($to_old) {
	    ($adr, $err) = &pr_addr($oldresp);
	    if ($err ne "") {
		$ed_err = "$errmsg\n$err";
		last LOCKED;
	    }
	    $mail_to{&tolower($adr)} = 1;
	}
	if ($to_new) {
	    ($adr, $err) = &pr_addr($input{'Responsible'});
	    if ($err ne "") {
		$ed_err = "$errmsg\n$err";
		last LOCKED;
	    }
	    $mail_to{&tolower($adr)} = 1;
	}

	# Apply the changes and send the new PR
	$newpr = &unparse_pr("");
        #print $newpr;
	#print "opening |$PR_EDIT > /tmp/wwwgnats.$$ 2>&1\n";
	unlink("/tmp/wwwgnats.$$");
	if (!open(PREDIT, "|$PR_EDIT > /tmp/wwwgnats.$$ 2>&1")) {
	    $ed_err = "$errmsg\nError: can't invoke pr-edit\n";
	    last LOCKED;
	}
	print PREDIT $newpr;
	close(PREDIT);
	if ($?) {
	    $ed_err = "$errmsg\nError: pr-edit returns status $?, and reports:\n";
	    if (!open(PREDIT, "/tmp/wwwgnats.$$")) {
		$ed_err .= "(whoops, no output from pr-edit found; couldn't open /tmp/wwwgnats.$$)\n";
	    } else {
		$ed_err .= join("\n",<PREDIT>);
		close(PREDIT);
	    }
	    unlink("/tmp/wwwgnats.$$");
	    last LOCKED;
	}
	unlink("/tmp/wwwgnats.$$");
	#print "</PRE>";
    }

    # Unlock the PR
    #print "unlocking\n";
    system("$PR_EDIT --unlock $semipr");
    # if we got here via a last, report the error and quit
    if ($ed_err ne "") {
	print "<PRE>";
	print $ed_err;
	print "</PRE>";
	return;
    }

    # Email-notify all concerned parties
    #print "---------------------------------</pre>\n";
    
    
    local($mail_to);
    $mail_to = join(", ", sort(keys(%mail_to)));

    if ($mail_to ne "") {
	if (open(MAILER, "|$MAILER")) {
	    $msg = 
"To: $mail_to
From: $GNATS_ADDR, $nEditor{$input{'Editor'}}
Subject: $semipr Change Information

Synopsis: $oldsyn

$change_msg
";
	    print MAILER $msg;
	    print MAILER "$mail_to\n";
            sleep 3;
	    close(MAILER);
	    sleep 3;
	    # Display message
	   
  # Display title
    print "<head><title>Problem Report editing</title></head>
<body>
";
print 
"<H3>Your changes to PR $pr were filed to the database.</H3>
The parties concerned were notified via e-mail as follows:
<br><pre>$msg</pre>
";
	} else {
	    print "Error: can't run $MAILER\n";
	}
    }
 


    if ($chdomain>0) {  # We no longer need it, we do not re-submit the problem
			# report. Jesus 6/12/96.

#

	$fieldvalues{'State'}="Open";
	$fieldvalues{'Category'}=$input{$estrin};
#	print "<h1>$input{$estrin}</h1>";
#	print "<h1>$fieldvalues{\"Category\"}</h1>";
	$prtext = &unparse_pr("send");


	@lins=split(/Number:/,$prtext);
	$i=0;
	$prtext="Number:";

	foreach $li (@lins) {
	    if ($i>0) {
		$prtext.=$li;
	    }
	    $i++;
	}


 open(MAIL, "|$MAILER") || die "Error while invoking sendmail";
# en el From ponia originalmente $fieldvalues{\"Email\"}
    print MAIL
"To: $GNATS_ADDR
Subject:$fieldvalues{\"Synopsis\"}
From: $fieldvalues{\"Reply-To\"} ($fieldvalues{\"Originator\"})
Reply-To:$fieldvalues{\"Reply-To\"}
X-send-pr-version: $GNATS_VER
$prtext";
#	print "<h1>Email:$fieldvalues{\"Email\"}</h1>";
#	print"<h1>El unformatted: $fieldvalues{\"Unformatted\"}</h1>";
#  print "<h4>$prtext</h4>";
    close(MAIL);


    }
}

#################### Quick query

sub query_quick {
    # Print title
    print "<head><title>Quick summary of Problem Reports</title></head>
<H2>Quick summary of Problem Reports:</H2>
<body>
";
    local($quickfmt,@restrict)=@_;

    # Convert $quickfmt to index into @quickfmt
    LOOP: for ($i=0; $i<@quickfmt; $i++) {
	if ($quickfmt eq $quickfmt[$i]) {
	    $quickfmt=$i;
	    last LOOP;
	}
    }
    # Split restrictions into key,value pairs
    # Collapse multiple selections with same key
    # Store collapsed restrictions in %restrict
    local($oldkey, $oldval);
    local(%restrict);
    foreach (@restrict) {
	$_ = &tolower($_);
	$_ = &cgi_trans($_);
	local($key,$val) = split(/=/);
	if ($key ne $oldkey) {
	    if ($oldval ne "") {
		$restrict{$oldkey} = $oldval;
	    }
	    $oldkey = $key;
	    $oldval = "";
	    $oldval = $val if ($val ne "");
	} else {
	    # just continue adding to old restriction
	    $oldval .= "|" if ($oldval ne "");
	    $oldval .= "$val" if ($val ne "");
	}
    }
    # Could have put a sentinal on the end of @restrict, but let's duplicate
    # code instead.
    if ($oldval ne "") {
	$restrict{$oldkey} = $oldval;
    }
   
     if ($DATEVALUE eq "manual+input") {
	print "<br><FORM ACTION=\"http:$SCRIPT_NAME/quick\">\n";
	print "<INPUT NAME=\"quickfmt\" TYPE=\"hidden\" VALUE=$_[0]>";
	
        foreach (keys(%restrict)) {
	    print "<INPUT NAME=\"$_\" TYPE=\"hidden\" VALUE=\"$restrict{$_}\">" if ($restrict{$_} ne "" && $_ ne "date");
	}
	print "<INPUT NAME=\"Date\" TYPE=\"hidden\" VALUE=\"manual input\">\n";
	&dates_manual_input;
	print "<br>Enter start date (7 days ago by default): <INPUT NAME=\"date_start\" VALUE=\"$seven_days_ago\">\n";
	print "<br>Enter end date (today by default): <INPUT NAME=\"date_end\" VALUE=\"$date_of_today\">\n";
	print "<br><br><INPUT TYPE=\"submit\" VALUE=\"Click here\" >      <INPUT TYPE=\"reset\" value=\"Default\">\n";
	print "<br></FORM>\n";
	print "</body></html>\n";
    }
    else {

    local($opts);
    local(@prs);
    # Read in quick format list of pr's matching query
    # If querying by person, then do two queries: originator and responsible
    if ($restrict{"person"} ne "") {
	$fullname = $restrict{"person"};
	# Look up bugs for which this person is the originator.
	if ($fullname eq "any") {
	    $opts = "--state=\"open|assigned|feedback\"";
	} else {
	    $oldval = $fullname;
	    # Turn underscores and spaces into regular expression
	    # that match either underscores or spaces
	    # (Our database sometimes puts underscores instead of spaces).
	    $oldval =~ s/[\s_]/[ _]/g;
	    $oldval =~ s/\[ _\]([1-9])\|/[ _][ _]$1\|/g;
            $oldval =~ s/\[ _\]([1-9])$/[ _][ _]$1/;
	    # Handle bugs with no known originator
	    if ($oldval eq "nobody") {
		$oldval = "nobody|^\$";
	    }
	    # Convert this key into a query-pr option
	    $opts = " --originator=\"$oldval\"";
	    # The originator cares about bugs which are in feedback state.
	    $opts .= " --state=\"feedback\"";
	}
	# suppress looking for originator since it can be any user
	#open(PIPE,"$GNATS_BIN/query-pr -i $opts|") || die "Can't open";
	#@prs = <PIPE>;
	#close(PIPE);

	# Look up bugs for which this person is the responsible party.
	# Convert person's name into nickname
	$nickname = $fullname2nametag{$fullname};
	# Golly, maybe the spaces have been replaced with underscores.
	if ($nickname eq "") {
	    $fullname =~ s/_/\040/g;
	    $nickname = $fullname2nametag{$fullname};
	}
	if ($nickname ne "") {
	    # Convert this key into a query-pr option
	    $opts = " --responsible=\"$nickname\"";
	    $dom=$domain;
	    $dom =~ s/^-//;
	     print "<pre> <strong>In domain $dom:</strong> </pre>\n";
	    # Responsible person cares about bugs which are open or assigned.
	     foreach $option (@nCategory) {
		if ($option ne "") { 
	    $opts .= " --state=\"open|assigned|feedback\" --category=$option";
#	    print "<pre>query-pr -i $opts\n</pre>\n";
	    open(PIPE,"$GNATS_BIN/query-pr -i $opts 2>/dev/null |") || die "Can't open";
	     $opts = " --responsible=\"$nickname\"";
	    @prs = (@prs,<PIPE>);
	    close(PIPE);
	}
	    }
	}
		else {
	    #print "Warning: $fullname has no nickname.\n";
	    ;
	}
    } else {
	# Output restrictions as query-pr options
	foreach (keys(%restrict)) {
	    $oldkey = $_;
	    $oldval = $restrict{$oldkey};
	    # If "any" was given, don't bother using this key
	    if ($oldval !~ /\bany\b/) {
		# Turn underscores and spaces into regular expression
		# that match either underscores or spaces
		# (Our database sometimes puts underscores instead of spaces).
		$oldval =~ s/[\s_]/[ _]/g;
   		$oldval =~ s/\[ _\]([1-9])\|/[ _][ _]$1\|/g;
                $oldval =~ s/\[ _\]([1-9])$/[ _][ _]$1/;
		# Convert this key into a query-pr option
		$opts .= " --$oldkey=\"$oldval\"";
	   #However if "any" was chosen for the category then we still
	   #want to restrict the listing to the problem reports for
	   #the current domain
	    } elsif ($oldkey =~ /\bcategory\b/) {
                if ($oldval =~ /\bany\b/) {
                $anyopts = join("|",@nCategory);
                $anyopts =~ s/^\|//;
		$opts .= " --category=\"$anyopts\""; 
	    }
	    }
	}
#     
#      Print statement for the test system to see the options of 
#      the query in the Web page
#
#	print "<pre>query-pr -i $opts\n</pre>\n";
#
	open(PIPE,"$GNATS_BIN/query-pr -i $opts 2>/dev/null |") || die "Can't open";
	@prs = <PIPE>;
	close(PIPE);
    }
    
   
#    @prs = sort by_priority_and_number (@prs);

    if (@prs == 0) {
	print "<h3>No problem reports match your query.</h3>\n";
	return;
    }
    print "<pre>\n";
    # Print field headers.
    local($QUICKFMT, $WIDTH, $fstring, $str);
    $fstring = "";
    foreach (@field) {
	($QUICKFMT, $WIDTH)=split(/:/,$field{$_});
	if ($QUICKFMT <= $quickfmt) {
	    $fstring .= &truncstr($_, $WIDTH) . " ";
	}
    }
    print "     ",$fstring,"\n"; 

    opendir(MYDIR,"$GNATS_LIB/../www/Web") || die "Can't open listing";
#    opendir(MYDIR,"$GNATS_LIB/../lists") || die "Can't open listing";
    local(@filelist)=readdir MYDIR;
    local($filename);
    foreach $filename(@filelist) {
      if ($filename =~ m,^listing\d+,) {
	unlink("$GNATS_LIB/../www/Web/$filename");
      }
    }
    closedir(MYDIR);    
	    
      # Print each PR in result as link to full text 
     foreach (@prs) {
	s/\s*\|\s*/|/go;
        ($PRIORITY,
        $NUMBER, 
	$CATEGORY,
	$SYNOPSIS,
	$CONFIDENTIAL,
	$SEVERITY,
	$RESPONSIBLE,
	$STATE,
	$CLASS,
	$SUBMITTER,
	$ARRIVAL_DATE,
	$ORIGINATOR,
        $START_DATE,
        $END_DATE,
	$RELEASE ) = split(/\|/, $_);
	$SEVERITY = $quickSeverity[$SEVERITY];
	$PRIORITY = $quickPriority[$PRIORITY];
	$STATE = $nState[$STATE];
	$CLASS = $nClass[$CLASS];

	$fstring = sprintf("%s", substr("    ", 0, (length($NUMBER)<5)?4-length("$NUMBER"):1));
	# @field is an array of the variable names $NUMBER, etc., in presentation order.
	# %field tells which quickfmt level and ?below? to print this variable
	#       in, and how wide to print it.
	foreach (@field) {
	    ($QUICKFMT, $WIDTH)=split(/:/,$field{$_});
	    if ($QUICKFMT <= $quickfmt) {
		$str = eval "\$$_";
		$fstring .= &truncstr($str, $WIDTH) . " ";
	    }
	}
	&listing($NUMBER) if ($do_listing == 1);
	print "<a href=http:$SCRIPT_NAME/full/$NUMBER>$NUMBER</a> ",&html_escape($fstring),"\n"; 
    }
	    print "</pre>\n";
	    print "<hr>";
	    print  "<H4>You can also see <a href=http:/file/listing$$>the listing</a> of the matching Problems Reports.</H4>\n" if ($do_listing == 1);
	    $do_listing=0;
	    }
}


###########################
sub query_summary {
    # Print title
    print "<head><title>Summary of active Problem Reports by person and status</title></head>
<H2>Summary of active Problem Reports by person and status:</H2>
<body>
";
    @prs == 0;
    #print "<pre>query-pr -i --state=\"open|assigned|feedback\" \n</pre>\n";
  
    foreach $option(@nCategory){
	#print"<h3> $option<h3>";
	
	if ($option ne  "") {
	
	  #  print "<h3> $GNATS_BIN/query-pr -i --state=\"open|assigned|feedback\" --category=$option <h3>";
    open(PIPE,"$GNATS_BIN/query-pr -i --state=\"open|assigned|feedback\" --category=$option 2>/dev/null |") || die "Can't open";
	@prss = <PIPE>;
    close(PIPE);
	#print "<h3> $prss <h3>";
	push(@prs,@prss);
              }
    }
    if (@prs == 0) {
	print "<h3>No problem reports match your query.</h3>\n";
	return;
    }
    # Count bugs by person.
    # Print each PR in result as link to full text 
    local(%counts,%names);
    foreach (@prs) {
	s/\s*\|\s*/|/go;
	($PRIORITY, 
	 $NUMBER,
	$CATEGORY,
	$SYNOPSIS,
	$CONFIDENTIAL,
	$SEVERITY,
	$RESPONSIBLE,
	$STATE,
	$CLASS,
	$SUBMITTER,
	$ARRIVAL_DATE,
	$ORIGINATOR,
        $START_DATE,
	$END_DATE,
	$RELEASE ) = split(/\|/, $_);
	$STATE = $nState[$STATE];
	#print "<pre>\n";
	#print "$STATE, $ORIGINATOR, $RESPONSIBLE    \n";
	# Figure out which person this bug is waiting on, if any
	if ($STATE eq "open" || $STATE eq "assigned" || $STATE eq "feedback") {
	    # Waiting on responsible person
	    # Convert nickname to fullname
	    $nickname = $RESPONSIBLE;
	    $nickname = &tolower($nickname);
	    $fullname = $nametag2fullname{$nickname};
	    if ($fullname eq "") {
		$fullname = $nickname;
		
	    }

	} 
	#elsif ($STATE eq "feedback") {
	#    $fullname = $ORIGINATOR;
	#    $fullname = &tolower($fullname);
	#    $fullname =~ tr/_/\040/;

	#}
	if ($fullname eq "") {
	    $fullname = "nobody";

	}

	if ($STATE eq "open" || $STATE eq "assigned" || $STATE eq "feedback") {
	   # print "counts{$fullname._.$STATE}++\n";
	    $counts{$fullname."_".$STATE}++;
	    $names{$fullname}++;
	}
	#print "\n";
    } 
    #print "</pre>\n";

    # Print field headers.
    print "<pre>\n";
    local(@states) = ("open", "assigned", "feedback");
    local($fstring, $str);
    $fstring = &truncstr("", 20)."   ";
    foreach (@states) {
	$fstring .= &truncstr($_, 10) . " ";
    }
    print $fstring,"\n"; 
    # Print counts per person.
    foreach $fullname (sort(keys(%names))) {
	$fstring = &truncstr($fullname, 20)."   ";
	local($_fullname) = $fullname;
	$_fullname =~ tr/ /_/;
	$fstring =~ s/(\s*)$//;
	print "<a href=http:$SCRIPT_NAME/quick?quickfmt=regular&Person=$_fullname&Date=&Multitext=>$fstring</a>$1"; 
	$fstring = "";
	foreach (@states) {
	    $str = $counts{$fullname."_".$_}+0;
	    $fstring .= &truncstr($str, 10) . " ";
	}
	print "$fstring\n";
    }
    print "</pre>\n";
    print "<HR>";

}



##############################    
sub query_summary_cat {
    # Print title
    print "<head><title>Summary of Problem Reports by category and status</title></head>
<H2>Summary of Problem Reports by category and status:</H2>
<body>
";
    #print "<pre>query-pr -i \n</pre>\n";
    
    foreach $option (@nCategory) {
	if ($option ne "") {
	    #print "<h1>$option</h1>";
	   # open(PIPE,"GNATS_BIN/query-pr -i --category=$option |") || die "Can't open";
	    open(PIPE,"$GNATS_BIN/query-pr -i --category=$option 2>/dev/null |") || die "Can't open";
	    @prss = <PIPE>;
	   # print"<h1>:$option:</h1>";
	   # print"<h2>@prss<h2>";
	    push(@prs,@prss);
	    close(PIPE);
	}
    }
	if (@prs == 0) {
	    print "<h3>No problem reports match your query.</h3>\n";
	    return;
    }
    # Count bugs by category.
    # Print each PR in result as link to full text 
    local(%counts,%names,%states);
 
    foreach (@prs) {
	s/\s*\|\s*/|/go;
	( $PRIORITY,
	 $NUMBER,
	 $CATEGORY,
	$SYNOPSIS,
	$CONFIDENTIAL,
	$SEVERITY,
	$RESPONSIBLE,
	$STATE,
	$CLASS,
	$SUBMITTER,
	$ARRIVAL_DATE,
	$ORIGINATOR,
        $START_DATE,
        $END_DATE,
	$RELEASE ) = split(/\|/, $_);
	$STATE = $nState[$STATE];

	#print "$STATE, $ORIGINATOR, $RESPONSIBLE    ";
	#print "counts{$CATEGORY._.$STATE}++";
	$counts{$CATEGORY."_".$STATE}++;
	$names{$CATEGORY}++;
	$states{$STATE}++;
	#print "\n";
    } 
    #print "</pre>\n";

    # Print field headers.
    print "<pre>\n";
    #local(@states) = sort(keys(%states));
    local(@states) = ("open", "assigned", "feedback", "closed", "suspended");
    local($fstring, $str);
    $fstring = &truncstr("", 20)."   ";
    foreach (@states) {
	$fstring .= &truncstr($_, 10) . " ";
    }
    print $fstring,"\n"; 
    # Print counts per person.
    foreach $CATEGORY (sort(keys(%names))) {
	$fstring = &truncstr($CATEGORY, 20)."   ";
	$fstring =~ s/(\s*)$//;
	print "<a href=http:$SCRIPT_NAME/quick?quickfmt=regular&Category=$CATEGORY&Date=&Text=>$fstring</a>$1"; 
	$fstring = "";
	foreach (@states) {
	    next if ($_ eq "");
	    $str = $counts{$CATEGORY."_".$_}+0;
	    if ($str > 0) {
		# Who's gonna answer the following query?
		$fstring .= "<a href=http:$SCRIPT_NAME/quick?quickfmt=regular&Category=$CATEGORY&Date=&State=$_>$str</a>"; 
		$fstring .= " " x (11-length($str));
	    } else {
		$fstring .= &truncstr($str, 10) . " ";
	    }
	}
	print "$fstring\n";
    }
    print "</pre>\n";
    print "<HR>";

}
    
######################## Full query
sub query_full
{
    local($pr) = $_[0];
    print "<head><title>Full Problem Report Text</title></head>
<body>
";
    if ($pr eq "") {
	print "<H3>Sorry</H3>\n";
	print "You must specify the number of the problem report to view.\n";
	return;
    }
    $err = &read_pr($pr, "");
    if ($err ne "") {
	print "$err\n";
    } else {
	print "
<FORM ACTION=\"http://nnnn.nnn.nn/edit$domain$path2\" >
<INPUT TYPE=\"submit\" VALUE=\"Click here to edit\" >
<INPUT NAME=\"pr\" TYPE=\"hidden\" VALUE=\"$pr\">
</FORM>
<H2>Full text of Problem Report number $pr :</H2>
";
	print "<pre>\n";
	$prtext = &html_escape(join("",@oldpr));
	$prtext =~ s/&gt;([\w-]*):/<strong>$1<\/strong>:/g;
	$prtext =~ s/Reply-To: ([\w-@\.]*)\n/
	    $subject=$fieldvalues{"Synopsis"};
	
	    if ($1 eq "")
	    { join('', $1); }
	else
	{ join('', 'Reply-To: <a href="\/htbin\/sendmailto.pl\/',$username,'\/', $eladdress,'\/', $1,'\/', $subject, '">', $1, "<\/a>\n"); }/e;

# patch to allow reply to bugs, so user can apend info to Pr, also
# the subject field of the message should be changed so bugs understands it
	$subject=join("/",$fieldvalues{"Category"},$pr);
	$prtext =~ s/To: ([\w-@\.]*)\n/
	    if ($1 eq "")
	    { join('', $1); }
	else
	{ join('', 'To: <a href="\/htbin\/sendmailto.pl\/',$username,'\/', $eladdress,'\/', $1,'\/', $subject, '">', $1, "<\/a>\n"); }/e;
# end of patch................................
	print $prtext;
	print "</pre>\n";
	print "<HR>";

    }
}

############################# Main Menu
#
# Very first page of front end
#
sub main_menu {
    # Display title
    print "<head><title>CN Problem Reporting System</title></head>
<H2><a href=\"http://wwwcn.cern.ch/Welcome.html\">CN</a>
 Problem Reporting System</H2>
<body>
<strong>
";

print "
Click
<a href=\"$GNATS_DOC\">
here
</a>
for an introduction to the GNATS Problem Reporting System
or choose one of the following commands:
<ol>

<li><FORM ACTION=\"http:$SCRIPT_NAME/send_pr\">
<INPUT TYPE=\"submit\" VALUE=\"Submit a new problem report\">
</FORM>
<li><FORM ACTION=\"http:$SCRIPT_NAME/full\">
Enter Problem Report number <INPUT NAME=\"pr\" SIZE=6>
and click<INPUT TYPE=\"submit\" VALUE=\"here \"> to view/edit an existing report
</FORM>

<li><FORM ACTION=\"http:$SCRIPT_NAME/summary\">
<INPUT TYPE=\"submit\" VALUE=\"Get a summary of active problems by status and person\">.
</FORM>
<li><FORM ACTION=\"http:$SCRIPT_NAME/summary_cat\">
<INPUT TYPE=\"submit\" VALUE=\"Get a summary of all problems by status and category\">.
</FORM>
<li><FORM ACTION=\"http:$SCRIPT_NAME/custom_sum\">
<INPUT TYPE=\"submit\" VALUE=\"Keyword search utility\">.
</FORM>
<li><FORM ACTION=\"http:$SCRIPT_NAME/report\">
<INPUT TYPE=\"submit\" VALUE=\"Report generation\">.
</FORM>
</DL>
</ol>
</strong>
";
}

######################## Quick query
sub custom_sum 
{
 # Display title
   
print "<html>\n";

 print "<head><title>Keyword search</title></head>
<H1>Keyword search</H1>";
    print "<hr>\n";
    print "<li><strong>Use the following form for a keyword search of the database:</strong>";
print "</head>";

print "<body>";
    print "<br><FORM ACTION=\"http:$SCRIPT_NAME/quick\">\n";

    # Choose quick output format.
    print "Select \n";
    print "<SELECT NAME=\"quickfmt\">\n";
    foreach (@quickfmt) {
	print "<OPTION", ($_ eq "regular") ? " SELECTED" : "", "> $_\n";
    }
    print "</SELECT> output format. <BR>\n";

    local($mode);

    print "<BR>Restrict the output by specifying a value for one or more <a href=\"http://consult.cern.ch/writeup/gnats/gnats_1.html#SEC6\">problem report fields</a>:\n";

  print "
  <pre>
<a href=\"/file/help.html#severity\">Severity</a>  :<input type=\"checkbox\" name=\"Severity\" value=\"any\" checked> any  <input type=\"checkbox\" name=\"Severity\" value=\"non-critical\"> non-critical  <input type=\"checkbox\" name=\"Severity\" value=\"serious\"> serious       <input type=\"checkbox\" name=\"Severity\" value=\"critical\"> critical

<a href=\"/file/help.html#priority\">Priority</a>  :<input name=\"Priority\" type=\"checkbox\" value=\"any\" checked> any  <input name=\"Priority\" type=\"checkbox\" value=\"low\" > low           <input name=\"Priority\" type=\"checkbox\" value=\"medium\"> medium        <input name=\"Priority\" type=\"checkbox\" value=\"high\"> high


<a href=\"/file/help.html#class\">Class</a>     :<input name=\"Class\" type=\"checkbox\" value=\"any\" checked> any  <input name=\"Class\" type=\"checkbox\" value=\"support\" > support       <input name=\"Class\" type=\"checkbox\" value=\"scheduled\"> scheduled     <input name=\"Class\" type=\"checkbox\" value=\"duplicate\"> duplicate
                   <input name=\"Class\" type=\"checkbox\" value=\"sw-bug\"> Software      <input name=\"Class\" type=\"checkbox\" value=\"doc-bug\"> Documentation <input name=\"Class\" type=\"checkbox\" value=\"change-request\"> Change Request 

</pre>\n";
        

    # Loop over output restrictions (Category, State, Responsible).
    foreach (@quickrestr) {
	# Make sure choices fit within window
	#$mode = $HTTP_AGENT=~/X Win/ && eval"\@n$_">20 ? "SIZE=10" : "";
	$mode = eval"\@n$_">30 ? "SIZE=2" : "";
	# Let user select more than one choice for "State".
	if ($_ eq "State") {
 	    $mode = "SIZE=". eval"\@n$_";
	    $mode .= " MULTIPLE";
	}
        $helpfile = $_;
        $helpfile =~ tr/A-Z/a-z/;
	print "<DT> <a href=\"/file/help.html#$helpfile\">$_</a>\n";
        print "<DD>";
       print "<SELECT $mode NAME=\"$_\">\n";
	# Refer to arrays @nCategory, @nState, @nResponsible as appropriate.
	# Note use of eval.
        foreach $option (eval "\@n$_") {
	    $option= "any" if (!$option);
	    print "<OPTION", ($option eq $quickrestr{$_}) ? " SELECTED" : "", "> $option\n"; 
	}
        print "</SELECT>";
    }

    # Loop over freeform search restrictions (Text, Multitext).
    print "</DL>\n";
    print "and/or specifying a 
<a href=\"http://consult.cern.ch/writeup/gnats/gnats_6.html\">freeform text search</a>
on
<a href=\"http://consult.cern.ch/writeup/gnats/gnats_1.html#SEC6\">any GNATS field</a>.\n";
    print "<DL>\n";
    foreach ("Arrival-Date, Date of last modification") {
	print "<DT><a href=\"/file/help.html#date\"> $_</a>\n";
        print "<DD>\n";
      	print "<SELECT NAME=\"Date\">\n";
	print "<OPTION SELECTED> any\n";
	print "<OPTION> manual input\n";
	print "<OPTION> today\n";
	print "<OPTION> yesterday\n";
	print "<OPTION VALUE=\"last week\"> last 7 days\n";
	print "<OPTION VALUE=\"last two weeks\"> last 14 days\n";
	print "<OPTION VALUE=\"last month\"> last 30 days\n";
	print "</SELECT>\n";
    }

    print "<BR><BR>\n<DT><a href=\"/file/help.html#occurencetime\"> Date and Time of occurence</a>\n";
    print "<DD>\n";
    print "<INPUT NAME=\"StartDate\" SIZE=\"16\">\n";

    print "<BR><BR>\n<DT><a href=\"/file/help.html#occurencetime\"> Date and Time of end</a>\n";
    print "<DD>\n";
    print "<INPUT NAME=\"EndDate\" SIZE=\"16\">\n";

    print "<DT><a href=\"/file/help.html#synopsis\"> Synopsis</a>\n";
    print "<DD>\n";
    print "<INPUT NAME=\"Text\" SIZE=\"16\">\n";

    print "<DT><a href=\"/file/help.html#description\"> Description</a>\n";
    print "<DD>\n";
    print "<INPUT NAME=\"Multitext\" SIZE=\"32\">\n";

print "</DL>
<BR>Finally, <INPUT TYPE=\"submit\" VALUE=\"click here to search\">. <BR>
</FORM>
</ol>
<HR>
</body>
</html>
";

}


######################### send-pr
sub send_pr 
{
    if ($username eq "1") {
	$username = ""
	}
if ($eladdress eq "1") {
	$eladdress = ""
	}
#print &PrintHeader;
print "<html>\n";
print "<head>\n";

# The domain of the problem report is put in the request field
# example: http://your_server.your_domain/htbin/send_gnats/UWC/ -> -UWC

# default for start-date field
&dates_manual_input;

# Print the document
print <<"EOM";

<title>Submit a New Problem Report</title>
</head>

<body>
<h1>Submit a New Problem Report</h1>
<hr>

Please fill out the following form to describe the problem that you wish to 
report. Help can be obtained on any of the fields by clicking on the 
highlighted keywords

<hr>
<FORM METHOD=\"POST\" ACTION=\"http:$SCRIPT_NAME/handle_send_pr\">


<pre>
<a href=\"/file/help.html#severity\">Severity</a>     :<input name=\"Severity\" type=\"radio\" value=\"non-critical\" checked>non-critical  <input name=\"Severity\" type=\"radio\" value=\"serious\">serious       <input name=\"Severity\" type=\"radio\" value=\"critical\">critical
<a href=\"/file/help.html#priority\">Priority</a>     :<input name=\"Priority\" type=\"radio\" value=\"low\" checked>low           <input name=\"Priority\" type=\"radio\" value=\"medium\">medium        <input name=\"Priority\" type=\"radio\" value=\"high\">high
<a href=\"/file/help.html#class\">Class</a>        :<input name=\"Class\" type=\"radio\" value=\"support\" checked>support       <input name=\"Class\" type=\"radio\" value=\"scheduled\">scheduled     <input name=\"Class\" type=\"radio\" value=\"duplicate\">duplicate<BR>              <input name=\"Class\" type=\"radio\" value=\"sw-bug\">software-bug  <input name=\"Class\" type=\"radio\" value=\"doc-bug\">documentation <input name=\"Class\" type=\"radio\" value=\"change-request\">change-request
 
<a href=\"/file/help.html#originator\">Originator</a>   :<input name=\"Originator\" value=\"$username\">

<a href=\"/file/help.html#email\">Email address</a>:<input name=\"Email\" value=\"$eladdress\" size=24><input type="hidden" name=\"Organization\" value=\"CERN\">

<a href=\"/file/help.html#occurencetime\">Date and Time</a>:<input name=\"Start-Date\" value=\"$default_for_start_date\"> when the problem occured

<a href=\"/file/help.html#enddatetime\">Date and Time</a>:<input name=\"End-Date\" value=\"\"> when the problem ended<input type="hidden" name=\"Release\" value=\"unknown\">

EOM

print "<a href=\"/file/help.html#synopsis\">Synopsis</a>      :"; 

$result=&read_subject;

    if ($result==1) {
	print "<select name=\"Synopsis\">\n";
	
        # open the domain specific subject file and dump the contents
	# here as options

	foreach $option (@nSubject) {
	    print "<OPTION>$option\n" if ($option);
	}
	print "</select>\n";
    }
    else 
    {
	print "<input name=\"Synopsis\">\n";
    }


print <<"EOM";

<a href=\"/file/help.html#category\">Category</a>     :<select name=\"Category\">


EOM

# open the domain specific problem category file and dump the contents
# here as options

foreach $option (@nCategory) {
    print "<OPTION>$option\n" if ($option);
}


print <<"EOM";
</select>

<a href=\"/file/help.html#environment\">Environment</a>: (Copy the result of 'uname -a' command here)
<textarea name=\"Environment\" rows=2 cols=80>
unknown
</textarea>

<a href=\"/file/help.html#description\">Description</a>:
<textarea name=\"Description\" rows=10 cols=80>
</textarea>

<a href=\"/file/help.html#repeat\">How to repeat</a>:
<textarea name=\"How-To-Repeat\" rows=5 cols=80>
</textarea>

<input type=\"submit\" name=\"submit\" value=\"Send the report\">      <input type=\"reset\" value="clear">
</pre>
</form>

<HR>
</body>
</html>
EOM
;
}

### 30-11-95 The following field was moved out of the problem report
### submission form. If the response is known then there is no problem.
### Alan Lovell
###
#<a href=\"/file/help.html#response\">Response</a>:
#<textarea name=\"Response\" rows=5 cols=80>
#</textarea>


######################## Report generation
sub report 
{
 # Display title
   
print "<html>\n";

 print "<head><title>Report generation</title></head>
<H1>Report generation</H1>";
   
print "<body>
<HR>
<H3>Please select one of the following templates:<BR><BR>
<a href=\"http:$SCRIPT_NAME/custom_sum\">Keyword search</a><BR><BR>
<a href=\"http:$SCRIPT_NAME/quick?quickfmt=regular&Severity=serious&Severity=critical&Priority=high&Category=any&State=any&Responsible=any&Date=last+week&Multitext=\">C5 Report</a><BR><BR>
<a href=\"http:$SCRIPT_NAME/quick?quickfmt=regular&Severity=any&Priority=high&Category=any&State=any&Responsible=any&Date=last+week&Multitext=\">Full Weekly Report</a><BR><BR>
<a href=\"http:$SCRIPT_NAME/quick?quickfmt=regular&Severity=any&Priority=any&Category=any&State=any&Responsible=any&Date=manual+input&Multitext=\">INSCM</a>

</H3>
<BR>
<HR>
</body>
</html>
";

}



