#! /usr/local/bin/perl -w
# CGI script that demonstrates how to store data
# from a form in a local text file.

#---------------------------------------------------------------------
# A more thorough explanation for how this script is used can be found
# in the file feedback.README
#---------------------------------------------------------------------

#use strict;

# directory for the raw feedback
$DIR="/home/bambam/leavens/WWW/ComS362/feedback/";

# file where the data will be stored
$OUTFILE=$DIR.(scalar localtime).".txt";

# where to send the user after processing the output
$FINALURL="../thanks.shtml";

# a signature line for validating raw input
$SIGNATURE="innagaddadavita";

# process POST input
if ($ENV{'CONTENT_LENGTH'} > 0) {
    # read POST data from STDIN
    read STDIN, $temp, $ENV{'CONTENT_LENGTH'};
    # add in GET data
    $temp.="&".$ENV{'QUERY_STRING'} if length $ENV{'QUERY_STRING'};
} else {
    # read only the GET data
    $temp=$ENV{'QUERY_STRING'};
}
# check the command line for offline debugging:
$temp=join("&", @ARGV, $temp) if ($#ARGV > -1);

# open the file
unless (open FILE, ">>$OUTFILE") {
    # error message 
    print "Content-type: text/plain\n\nCannot open $OUTFILE: $!\n";
} else {
    print FILE "$SIGNATURE\n";
    print FILE "-------------".(scalar localtime)."-------------\n";
    print FILE "    User agent: $ENV{'HTTP_USER_AGENT'}\n";
    print FILE "Remote address: $ENV{'REMOTE_ADDR'}\n";

    # split each keyword
    foreach ( split( /&/, $temp ) ) {
	# separate the key and value
	( $key, $val ) = split( /=/, $_, 2 );

	# translate + to spaces
	$key=~s/\+/ /g;
	$val=~s/\+/ /g;

	# translate %xx codes to characters
	$key=~s/%([0-9a-f]{2})/pack("c",hex($1))/gie;
	$val=~s/%([0-9a-f]{2})/pack("c",hex($1))/gie;

	# write the key and value
	print FILE "$key = $val\n";
    }
    close FILE;

    chmod 0600, $OUTFILE;
    chown 111, 52, $OUTFILE;

    # redirect browser to new URL
    print "Location: $FINALURL\n\n";
}
exit 0;
