#!/usr/local/bin/perl
##########################################################################
#################### read info for this year: ############################
do "../INFO.pl";
##########################################################################
$bodystmt='bgcolor="#009ebe"';
$title="Bulletin Board for Copper Mountain Conference";
$ThisDir="/www/faculty/copper/$Year/Messages";
$CopperMtHome="/faculty/copper/$Year/";

$addmesgfile="add.html";
$readmesgfile="read.cgi";
$mesgdir="$ThisDir/messages";

# the month and year you started the bulletin board
$startyear=($Year-1);
$startmonth=10;
##########################################################################


@months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
@months = qw(January February March April May June July August
			September October November December);
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime;
$year += 1900;


print "Content-type: text/html\n\n";
print "<!-- Virtual Doc produced by $readmesgfile -->\n";
print "<html>\n<head>\n<title>$title</title>\n";


chdir($ThisDir);

@VarNames=();
%VarValues=();

if (($ENV{"REQUEST_METHOD"} eq "GET") && ($ENV{"QUERY_STRING"} eq ""))
{
    # when we'll start looking from 
    $m = $startmonth;
    $y = $startyear;

    # a little html code
    print "<body $bodystmt>\n";
    print "<h1 align=\"center\">Select what you want</h1>\n";
    print "<p>Please fill out the form below to choose which messages\n";
    print "you would like to scan.<p>\n";
    print "<form method=\"get\" action=\"$readmesgfile\">\n";
    print "Which Month:\n";
    print "<select name=\"month\">\n";
    print "<option value=\"all\">All\n";

    # create the menu based on the files we have
    while (1)
    {
	# here we will try to open all the files that should be there
	# (from the startmonth/startyear until today)
	$filenamehtml = sprintf("%s/mesg%d.%02d.html",$mesgdir,$y,$m);
	$filenamecount = sprintf("%s/mesg%d.%02d.count",$mesgdir,$y,$m);
	# if we can read the message file
	if ( -f $filenamehtml) {
	    # add this month/year to the menu
	    printf("<option value=\"%d:%d\">%s, %d",$m,$y,$months[$m-1],$y);
	    # if there's a count asociated with it, add a blurb in the 
	    # menu
	    if (open(COUNT, $filenamecount))
	    {
		$_=<COUNT>;
		chop;
		# if the count is good
		if (/^(\d+)$/)
		{
		    print " ($1 msg)";
		}
		close(COUNT);
	    }
	    print "\n";
	}
	# increment month and year appropiately
	if (++$m > 12)
	{
	    $m=1;
	    $y++;
	}
	# this means we've gotten as far as we today's file
	#last if (($y>=$year)&&($m>($mon+1)));
	last if (($y>$year)||(($y==$year)&&($m>($mon+1))));
    } # making the month pull-down

    # give the rest of the form in html code
print <<EOR;
</select>

<p>
<h2>Search on what?</h2>

<h5>Please select one of the following ways to search for messages.</h5>

<UL>
<li><input type="radio" name="searchon" value="all" checked> All
<li><input type="radio" name="searchon" value="name"> Names
<li><input type="radio" name="searchon" value="email"> Email address
<li><input type="radio" name="searchon" value="subject"> Subjects
<li><input type="radio" name="searchon" value="number"> Numbers
</UL>
Please enter the string to seach over here.<br>
Seach String: <input type="text" name="searchstring" size="50"><br>
<center>
<input type="submit" value="Read Message(s)">
&nbsp &nbsp &nbsp &nbsp &nbsp &nbsp
<input type="reset" value="Reset to Defaults">
</center>
</form>

<p><hr><p>

<a href="$addmesgfile">Post</a> a message to the bulletin board.
<p><hr><p>
Return to <a href=\"$CopperMtHome\">main page</a>
</body>
</html>
EOR

    exit 0;
}


# this will get the url-encoded data string (all the stuff the
# user-entered into netscape) and put it in variable called $buffer
if ($ENV{"REQUEST_METHOD"} eq "POST")
{
    read (STDIN,$buffer,$ENV{"CONTENT_LENGTH"});
}
else
{
    $buffer=$ENV{"QUERY_STRING"};
}

# decode it and put stuff in array VarValues and hashtable VarValues
&DecodeUrl($buffer);
# give 'em easier to type names
@names = @VarNames;
%values = %VarValues;
# we don't need all that memory anymore
@VarNames=();
%VarValues=();

# get the month and year from the url-encoded string
($m,$y)= split(/:/,$values{"month"});

# start the html code
print "<body $bodystmt>\n";

# bad month
# 1. $m is not "all" and it's not a number
# 2. $m is a number but the year is not a number
# 3. $m is a number but it's larger than 12 or less than 1
if ( (($m !~ /^all$/) && ($m !~ /^\d+$/)) || (($m =~ /^\d+/) && ($y !~ /^\d+/))
    || (($m =~ /^\d+$/) &&($m > 12 || $m < 1)) )
{
    print "<h1 align=\"center\">Bad Format</h1>\n";
    print "The month field isn't in the correct format, which means\n";
    print "that you're doing something you shouldn't be.\n";
    print "<p>\n";
    print "Try using the offical <a href=\"$readmesgfile\">search page</a>\n";
    print "<p><hr>\n";
    print "<a href=\"$addmesgfile\">Post</a> a message to the bulletin\n";
    print "board\n<hr>\n";
    print "Return to <a href=\"$CopperMtHome\">main page</a>\n";
    print "</body></html>\n";
    exit 1;
}

# so now month should be either number (1-12) or "all" and year should be good

# if we are not supposed to looking through all months, and the url-encoded
# string contained a "number=..." field
if (($m !~ /^all$/) && ($values{"number"} =~ /^\d+$/))
{
    # this is the mesgno we want to look for
    $number=$values{"number"};

    # the name of the message file
    $filename=sprintf("%s/mesg%d.%02d.html",$mesgdir,$y,$m);

    # if that file's unavailible, give a message
    &MessageUnavailable($number,$m,$y) if (!open(MESG,$filename));
    $_ = <MESG>; # get header
    # go through each line of the file
    while (<MESG>)
    {
	chop;
	# found a new message in the file
	if (/<META MESGNO=(\d+)>/)
	{
	    next if ($1 != $number); # not our message number
	}
	# if not new message line, get next line
	else
	{
	    next;
	}

	# if we get here, it means we found the appropiate message in
	# the file
	# html code
	print "<h1 align=\"center\">Message #$number</h1>\n";

	# read in the whole message
	($date,$homepage,$name,$email,$subject,$message) = 
	    &readmessage(MESG);
	
	# print out date, header, and message
	print "Date Posted: ",$months[$m-1]," $date, ",$y,"<br>\n";
	&printheader($homepage,$name,$email,$subject);
	print "\n<font size=+1>Message</font>:<br>$message<hr><p>\n";
	print "<a href=\"$addmesgfile\">Post</a> a message to the\n";
	print "bulleting board.\n<hr>\n";
	print "Return to <a href=\"$CopperMtHome\">main page</a>\n";
	print "</body></html>\n";
	# don't do anything more
	exit 0;
    } # searching through file

    # if we get here, we didn't find the message we were looking for
    &MessageUnavailable($number,$m,$y);
    exit 0;
}

# if we get here, that means we have to search

# make sure we have a type of search
$values{"searchon"}="all" if
    ($values{"searchon"} !~ /(name|email|subject|all|number)/);
# if they didn't give a search string, then show them everything
$values{"searchon"}="all" if
    (($values{"searchon"} ne "all")&&(!$values{"searchstring"}));

# the string to search for (save me a little typing)
$str = $values{"searchstring"};

# do all the months
if ($m eq "all")
{
    $thismonth=$startmonth;
    $thisyear=$startyear;
}
# otherwise, start on the month user requested
else
{
    $thismonth=$m;
    $thisyear=$y;
}

# a little html code
print "<h1 align=\"center\">Messages</h1>\n";
print "The following messages matched your pattern for ";
if ($m eq "all")
    { print "all months"; }
else { print $months[$m-1]," ",$y; }
print ".<p>\nClick on the number to view the message body<p><hr>\n";

# this loop will be exited depending on whether we're looking at all months
# or just one month in particular
while (1)
{
    # the name of the current message file to look at
    $filename=sprintf("%s/mesg%d.%02d.html",$mesgdir,$thisyear,$thismonth);
    $printedit=0;

    # if we can get into the file
    if ((-f $filename)&&(open(MESG,$filename)))
    {
	$_ = <MESG>; # file header

	# them
	print "<h2>",$months[$thismonth-1]," ",$thisyear,"</h2>\n<dl>";
	$printedit=1;
	# go thru every line in the file
	while (<MESG>)
	{
	    chop;
	    # ok, this means the start of a message
	    if (/<META MESGNO=(\d+)>/)
	    {
		# the message number
		$number=$1;
		# read in the message
		($date,$homepage,$name,$email,$subject,$message) = 
		    &readmessage(MESG);
		# if we're searching on the name field, and we get a
		# match (which will also surround the match with
		# <strong>...</strong>)
		if (($values{"searchon"} eq "name")&&($name =~ 
		    s/($str)/<strong>$1<\/strong>/ig))
		{
                    print "<dt><a ";
                    print "href=\"$readmesgfile?month=$thismonth:$thisyear";
		    print "&number=$number\">\n";
                    print "Message <font size=+1>$number</font></a>\n";
		    print "<dd>";
		    &printheader($homepage,$name,$email,$subject);
		}
		# if we're searching on email field and get a match
		# (don't highlight match because that will throw off
		#  the "mailto:" thingy)
		elsif (($values{"searchon"} eq "email")&&($email =~
		    /$str/i))
		{
                    print "<dt><a ";
                    print "href=\"$readmesgfile?month=$thismonth:$thisyear";
		    print "&number=$number\">\n";
                    print "Message <font size=+1>$number</font></a>\n";
                    print "<dd>";
		    &printheader($homepage,$name,$email,$subject);
		}
		# searching on subject with match
		elsif (($values{"searchon"} eq "subject")&&($subject =~
		    s/($str)/<strong>$1<\/strong>/ig))
		{
                    print "<dt><a ";
                    print "href=\"$readmesgfile?month=$thismonth:$thisyear";
		    print "&number=$number\">\n";
                    print "Message <font size=+1>$number</font></a>\n";
                    print "<dd>";
		    &printheader($homepage,$name,$email,$subject);
		}
		# searching on the number and found a match
		elsif (($values{"searchon"} eq "number")&&($number =~
		    /^($str)$/))
		{
                    print "<dt><a ";
                    print "href=\"$readmesgfile?month=$thismonth:$thisyear";
                    print "&number=$number\">\n";
                    print "Message <font size=+1><strong>$number</strong>";
		    print "</font></a>\n";
                    print "<dd>";
                    &printheader($homepage,$name,$email,$subject);
		}
		# if we're searching all of the messages
		elsif ($values{"searchon"} eq "all")
		{
                    print "<dt><a ";
                    print "href=\"$readmesgfile?month=$thismonth:$thisyear";
		    print "&number=$number\">\n";
                    print "Message <font size=+1>$number</font></a>\n";
                    print "<dd>";
		    &printheader($homepage,$name,$email,$subject);
		}
	    } # one message in file
	} # the whole file
    } # it's a good file

    # at this point, we're done with that month/year file
    # give some html
    print "</dl><hr>\n" if $printedit;

    # if we had a specific month, we're done here so leave the outside while
    last if ($m ne "all");

    # otherwise, increment the month and year accordingly
    if (++$thismonth > 12)
    {
	$thismonth=1;
	$thisyear++;
    }
    # exit the loop after we do today's month/year file
    #last if (($thisyear>=$year)&&($thismonth>$mon+1));
    last if (($thisyear>$year)||(($thisyear==$year)&&($thismonth>$mon+1)));
} # all the files

print "<p><a href=\"$addmesgfile\">Post</a> a message on\n";
print "the bulletin board\n<hr>\n";
print "Return to <a href=\"$CopperMtHome\">main page</a>\n";
print "</body></html>\n";

exit 0;

###################################################################

sub MessageUnavailable
{
    local($number,$m,$y)=@_;
    print "<h1 align=\"center\">Message Unavailable</h1>\n";
    print "Sorry, but that message # $number of ",$months[$m-1]," ",$y;
    print "\nappears to be unavailable.<p>\n";
    print "<hr>\n";
    print "</body></html>\n";
    exit 1;
}

###################################################################

# reads one whole message assuming the file pointer is in the right place
# (the line after <META MESGNO=(\d+)> )
sub readmessage
{
    local($file)=$_[0];
    local($date,$homepage,$name,$email,$subject,$message,$header);
    $header=0;
    while (<$file>)
    {
	chop;
	if (/<META DATE=(\d+)>/)
	{
	    $date=$1;
	}
	elsif (/<META HOMEPAGE=(.+)>/)
	{
	    $homepage=$1;
	}
	elsif (/<META HEADER>/)
	{
	    $header=1;
	}
	elsif ($header && /Name:(.*)<br>/)
	{
	    $name=$1;
	}
	elsif ($header && /Email:(.*)<br>/)
	{
	    $email=$1;
	}
	elsif ($header && /Subject:(.*)<br>/)
	{
	    $subject=$1;
	}
	elsif (/<META BODY>/)
	{
	    while (<$file>)
	    {
		last if (/<META MESGEND>/);
		$message.=$_;
	    }
	    return ($date,$homepage,$name,$email,$subject,$message);
	}
    }
    return ($date,$homepage,$name,$email,$subject,$message);
}

###################################################################

sub printheader
{
    local($homepage,$name,$email,$subject) = @_;
    print "<font size=+1>Name</font>: ";
    print "<a href=\"$homepage\">" if $homepage;
    $name = "Anonymous" if (!$name);
    print $name if ($name);
    print "</a>" if $homepage;
    print "<br>\n<font size=+1>Email address</font>: ";
    $email = "None" if (!$email);
    print "<a href=\"mailto:$email\">" if ($email ne "None");
    print $email;
    print "</a>" if ($email ne "None");
    $subject = "None" if (!$subject);
    print "<br>\n<font size=+1>Subject</font>: $subject<br>\n";
}

###################################################################

sub DecodeUrl
{
    local($str) = $_[0]; # don't modify original string
    local(@entries,$val);

    %VarValues=(); @VarNames=(); # clear any old values
    @entries = split("&",$str); # split into entries

    #print STDOUT "Num = ",$#entries,"\n";

    # go through each entry, split into varname and value, remove
    # +'s and hex codes
    for (local($i)=0;$i<=$#entries;$i++)
    {
        #print STDOUT 'entry=',$entries[$i],"\n";

        # split into name and value
        ($VarNames[$i],$val) = split("=",$entries[$i]);

        #print STDOUT "name=",$names[$i]," val=",$val,"\n";

        $val =~ s/\+/ /g; # replace +'s with spaces
        # this is why we love perl--replace hex codes w/ ascii char
        # there's probably a better way to do this, but this seems to
        # work pretty well.
        1 while $val =~
            s/(.*)%([\da-fA-F]{2})(.*)/$val=sprintf("%s%c%s",$1,hex($2),$3)/eg;
	# get rid of ^M's
	$val =~ s/\r//g;
        $VarValues{$VarNames[$i]} = $val;

        #print STDOUT "-----------\n";
    }
    $i; # return the number of entries (not the highest index)
}

###################################################################

sub GetNumVars
{
    local($str) = $_[0]; # don't modify original string
    local(@temp);
    @temp = split("&",$str); # split around &'s, into entries
    $#temp + 1; # returns the number elements in $temp
}

###################################################################