#!/usr/bin/perl
#
# classifieds.pl
# version 980901
# copyright 1997-1998 by bo larsson
# all rights reserved
#
# this CGI program will allow you to maintain a set of categorized
# classified advertisements. It has the ability to either display or
# add classifieds.
#
# $the_path should be set to where the text files that will contain
# the classifieds are stored.
#
# bugs or feedback to bliss@seagull.net
# for information on how to use, visit http://www.seagull.net/bliss/

$the_path = "D:/Webs/ventworld/www/news/classifieds/files";

# Get the input and strip off all unwanted characters
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});

# Store the matching name and value pairs
foreach (split(/&/,$buffer))
{
	($NAM, $VAL) = split(/=/, $_);
	$VAL =~ s/\+/ /g;
	$VAL =~ s/%([0-9|A-F]{2})/pack(C,hex($1))/eg;
	$DATA{$NAM} = $VAL;
}

# Grab necessary variables
$returnURL = $DATA{'returnURL'};
$value = $DATA{'value'};
$category = $DATA{'category'};
$user_email = $DATA{'user_email'};
$user_name = $DATA{'user_name'};
$message = $DATA{'message'};
$message =~ s/\n/ /g;

print "Content-type: text/html\n\n";

# Check that category is a plain file name to prevent user
# from supplying things like ";cat /etc/passwd |"

$category =~ /^[\w-]+$/ || die "Invalid category given \"$category\"";

if ($value eq "Display")
{
	print "<FONT SIZE=+3>$category</FONT><P>\n";
	print "<TABLE BORDER=1 WIDTH=100% BGCOLOR=\"#FFFFFF\">";
	open (ADVERTISEMENTS, "$the_path/$category") || die "Can't open log file $category\n";
	
	while (<ADVERTISEMENTS>)
	{
		($email,$name,$msg,)=split(/\t/,$_);
		print "<TR>";
		print "<TD VALIGN=TOP>Send inquiries to: <A HREF=\"mailto:$email\">$name</TD>";
		print "<TD VALIGN=TOP>$msg</TD>";
		print "</TR>";
	}
	close(ADVERTISEMENTS);
	print "</TABLE>";
}
elsif ($value eq "Add")
{
	# do we have all the variables we need?
	if ($returnURL eq "") {
		print "ERROR: returnURL not set.\n"; }
	elsif ($value eq "") {
		print "ERROR: value not set.\n"; }
	elsif ($category eq "") {
		print "ERROR: category not set.\n"; }
	elsif ($user_email eq "") {
		print "ERROR: You did not enter your email address.\n"; }
	elsif ($user_name eq "") {
		print "ERROR: You did not enter your name.\n"; }
	elsif ($message eq "") {
		print "ERROR: You did not enter a message.\n"; }
	else
	{
		open (ADVERTISEMENTS, ">$the_path/$category") || print "Can't open log file $the_path/$category\n";
		flock(ADVERTISEMENTS,2);
		@entries = <ADVERTISEMENTS>;
		seek(ADVERTISEMENTS,0,0);
		print ADVERTISEMENTS "$user_email\t";
		print ADVERTISEMENTS "$user_name\t";
		print ADVERTISEMENTS "$message\n";
		print ADVERTISEMENTS @entries;
		flock(ADVERTISEMENTS,8);
		close (ADVERTISEMENTS);
		print "Your advertisement has been added to the $category category.<P>\n";
	}
}
else
{
	print "The option you selected doesn't exist. How did that happen?<P>\n";
}
print "<P>";
print "<A HREF=\"$returnURL\">Return to Classifieds</A>";
print "</BODY></HTML>";


