package TripodCGI;


################
# TripodCGI.pm #
#############################################################################
# TripodCGI is a module to help you deal with CGI input, which is the kind #
# of input your script can get from forms (as well as from specially-coded #
# links). When you have a form submit its information to your script, #
# you can use TripodCGI to grab some or all of the inputs that the form #
# provided, so that you can use them for your own nefarious ends ;) #
# #
# Of the functions below, the only two that you are likely to need to pay #
# attention to are param() and redirect(). param() is the function which #
# lets you grab CGI input. If you specify the name of a particular input #
# that you want to grab, param() will grab the value associated with the #
# input of that name. So if I have a form with a text input box named #
# 'address', and somebody types in '160 Water St.' and hits the submit #
# button, I can assign '160 Water St.' to the variable $form_address within #
# my form with this statement: #
# #
# $form_address = $CGI->param('address'); #
# #
# If you just want to know all of the names of the inputs returned by #
# the form, don't specify an input, and the names of all the inputs will be #
# returned as an array - like this: #
# #
# @all_inputs = $CGI->param(); #
# #
# The other function you might want to use is redirect(). redirect() lets #
# you specify the URL of a page or script that you want to move your #
# visitor to. You could use it like this: #
# #
# $CGI->redirect('http://www.tripod.com'); <- redirects to the Tripod #
# front page #
#############################################################################

sub new {
my $class = shift;
my $self = {};
bless $self, $class;
%data = ();
$self->_initialize();
return $self;
}


sub param {
my($self,$key) = @_;
return keys %data unless $key;

return undef unless defined($data{$key});

my @values = split("\0", $data{$key});
return wantarray ? @values : $values[0];
}


sub redirect {
my($self,$url) = @_;
return "Status: 302 Found\nLocation: $url\n" .
"URI: $url\nContent-type: text/html\n\n";
}


sub _initialize {
my $query_string = '';

if ($ENV{REQUEST_METHOD} eq 'POST') {
read(STDIN, $query_string, $ENV{CONTENT_LENGTH});
} else {
$query_string = $ENV{QUERY_STRING};
}

my($key,$val);

for (split(/&/, $query_string)) {
s/\+/ /g;
($key,$val) = split(/=/, $_, 2);

$key =~ s/%(..)/pack("c",hex($1))/ge;
$val =~ s/%(..)/pack("c",hex($1))/ge;

$val =~ s/\r\n/\n/g;
$val =~ s/\r/\n/g;

if (defined($data{$key})) {
$data{$key} .= "\0";
$data{$key} .= $val;
} else {
$data{$key} = $val;
}
}
}


1;