#!/usr/bin/perl
# ====================================================================
# @(#)  Decode email messages containing a CGI form posting
# ====================================================================
# $What: decode.pl$
#
# Extract information from an email message, posted from an html form 
# using <form method="post" action="mailto:emailid@usgs.gov">
#   reference: 
# http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type
#
# Written:  June 4, 1998  by  David Boldt
# Updated:  August 31, 1999  keep form values in same order
# Updated:  January 5, 2000  handle multiple messages in a file
# --------------------------------------------------------------------
$VERSION = (split(/\s+/,'$Revision: 1.0 $ '))[1];  # RCS magic
($me = $0) =~ s#^.*/##;

# -- Syntax and usage help

$USAGE = "USAGE:  $me filename
 version $VERSION
";

# -- check for input from file or stdin

if ($#ARGV > 0) {
    die $USAGE;
}
elsif ($#ARGV == -1) {
    die $USAGE  if -t 0;        # die if no file given and no stdin
    $file = '-';        # will read from stdin
}
elsif ($#ARGV == 0) {           # file to open
    $file = @ARGV[0];
}

open (MSG, "<$file")  || die "Unable to open file '$file'./n";
while (<MSG>) {
    next unless /&/;
    chop;
    %form = &load_FORM($_);
    foreach $key (@FORM_order) {
	$value = $form{$key};
	$value =~ s/\0/,/g;     # separate checkbox values with comma
	chomp($value);          # remove trailing newline
	$value =~ s/\n/\n\t/g;  # multiple lines get preceding tabs
	print "$key=$value\n";
    }
    undef(@FORM_order);         # reset global form-item order array
    print "\n";
}
close (MSG);

# --------------------------------------------------------------------
# Load associative array FORM with values, any multiple sections will
# be separated with nulls
# --------------------------------------------------------------------
sub load_FORM {
    local ($buffer) = @_;
    local (%FORM);
    local (@pairs);
    local ($name, $value);

    # split the name-value pairs on '&'
    @pairs = split(/&/, $buffer);
    # Go through the pairs and determine the name
    # and value for each form variable
    foreach $pair (@pairs) {
        ($name, $value) = split(/=/, $pair);
        $value =~ tr/+/ /;
        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
	$name =~ tr/+/ /;
        $name =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
	# separate multiple selections with nulls
	if ($FORM{$name}) {
	    $FORM{$name} .= "\0$value";
	}
	else {
	    $FORM{$name} = $value;
	    push(@FORM_order,$name);
	}
    }
    return %FORM;
}

