#!/usr/bin/perl
# Perl Script written by David Hardy david@planetmind.net
# copyright 2000 Planetmind Internetworks
# 
# usage: <!--#exec cgi="/cgi-bin/news.cgi"-->
# edit usage: http://www.planetmind.net/cgi-bin/news.cgi?action=edit
# Define Variables

$domain = $ENV{'SERVER_NAME'};
$domain =~ s/www\.//;
$basepath = "/home/chuck/dotanddoncoy/news";
$baseurl= "http://www.dotanddoncoy.com/news";
$scripturl = "http://www.dotanddoncoy.com/cgi-bin/cgiwrap/chuck/news_dd.cgi";
$homeurl="http://$domain";
$sitename = "Dot and Don Coy";

$newsfile = $basepath."/".$domain."_news.dat";
$archivefile = $basepath."/".$domain."_archive.dat";
$headerfile = $basepath."/news_header.html";
$footerfile = $basepath."/news_footer.html";
$maxitems=8;

# display type: 'table' or 'list'
$displaytype = "list";

################################
##  end user config.
################################



 @header = "<html><HEAD><TITLE>$sitename Announcements</title></head><BODY BGCOLOR=#EDCBB6><h2>$sitename 
Announcements</h2>";
 @footer = "</body></html>";


# Define arrays for the day of the week and month of the year.           #
    @days   = ('Sunday','Monday','Tuesday','Wednesday',
	       'Thursday','Friday','Saturday');
    @months = ('01','02','03','04','05','06','07',
		 '08','09','10','11','12');

    # Get the current time and format the hour, minutes and seconds.  Add    #
    # 1900 to the year to get the full 4 digit year.                         #
    ($sec,$min,$hour,$mday,$mon,$year,$wday) = (localtime(time))[0,1,2,3,4,5,6];
    $time = sprintf("%02d:%02d:%02d",$hour,$min,$sec);
    $year += 1900;

    # Format the date.                                                       #
    $date = "$months[$mon]/$mday/$year";


# Get the form input

if ($ENV{'REQUEST_METHOD'} eq 'GET') {
      # Split the name-value pairs
      @pairs = split(/&/, $ENV{'QUERY_STRING'});
   }
   elsif ($ENV{'REQUEST_METHOD'} eq 'POST') {
      # Get the input
      read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});

      # Split the name-value pairs
      @pairs = split(/&/, $buffer);
   }
   else {
      &error('request_method');
   }


    foreach $pair (@pairs) {
	($name, $value) = split(/=/, $pair);
	
	$name =~ tr/+/ /;
	$name =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
	$value =~ tr/+/ /;
	$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
      
   while ($value =~ /\n/) {
      $value =~ s/\cM//g;
      $value =~ s/\n\n/<p>/g;
      $value =~ s/\n/<br>/g;
   }

    $_ = $name;

      if (/news/) {
          
         push(@news,$value);
	}

	if (/url/) {

         if ($value =~ / |,|!|\&|\*|\?|\@|#/) {
            &error('You can\'t put spaces, exclamation points, commas, ampersands,asterisks, number signs, or question marks in file names! (Remember this - it will save you lots of trouble in Life.)');
         }
         push(@url,$value);
	}

	if (/exp_month/) {

          if (!$value) {
            &error('You left out part of the expire date.');
          }

         push(@exp_month,$value);
	}

	if (/exp_day/) {
	    if (!$value) {
            &error('You left out part of the expire date.');
          }
         push(@exp_day,$value);
	}

	if (/exp_year/) {
	    if (!$value) {
            &error('You left out part of the expire date.');
          }
         push(@exp_year,$value);
	}
   if (/desc/) {
         push(@long,$value);
	}
      if (/image/) {
         push(@image,$value);
	}

   if (/remove/) {
         ($nam,$val) = split(/_/);
         $remove .= $val." ";
	}


   $FORM{$name} = $value;
}

$action=$FORM{'action'};




#branch

if ($action eq "Update") {
   &check;
   &update;
   exit(0);
} elsif ($action eq "Edit Announcements" || $action eq "edit") {
 &edit;
 exit(0);
} else {
&display;
}

sub edit {

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

print qq!

<HTML><HEAD>
<title>$sitename Announcement Updater Form</title>
</head>
<BODY BGCOLOR="#D2BFD2">
<H1>$sitename Announcement Updater </H1>

<form action=$scripturl method=POST>
!;

$count=1;
open(DBASE, "<$newsfile") || print "I can't open $newsfile\n";
while (<DBASE>) {
     @oldnews = split(/\n/);


 foreach $line (@oldnews) { 

			($newsitem,$urll,$exp,$imagename,$desc) = split(/\|/, $line);

   $newsitem =~ s/<p>/\n\n/g;
   $newsitem =~ s/<br>/\n/g;
   
   $desc =~ s/<p>/\n\n/g;
   $desc =~ s/<br>/\n/g;


 
($itemmonth,$itemday,$itemyear) = split (/-/,$exp);

$test="0";
   if ($itemyear > $year){$test="1";}
   if ($itemmonth > $months[$mon] && $itemyear >= $year) {$test="1";}
   if ($itemmonth >= $months[$mon] && $itemyear >= $year && $itemday >= $mday) {$test="1";}      
      
  if ($test eq "1" ) {
   print qq!
	<table border=0 cellspacing=10><tr>
	<td><B>News Item $count Title:</B> <br><INPUT TYPE=text NAME="news$count" VALUE="$newsitem" SIZE=48></td></tr>
      <td><B>Image:</B> <br><INPUT TYPE=text NAME="image$count" VALUE="$imagename" SIZE=48><br></td></tr>
      <tr><TD>Long Desciption: <BR><TEXTAREA NAME="desc$count" WRAP=physical ROWS=10 COLS=80>$desc</TEXTAREA></td></tr>

      <tr><td>Page Name:<INPUT NAME="url$count" TYPE="text" SIZE=32,1 value=$urll><br>
 	Expires: <INPUT NAME="exp_month" TYPE="text" VALUE="$itemmonth" size=2,1> - <INPUT NAME="exp_day" 
TYPE="text" VALUE="$itemday" SIZE=2,1> - <INPUT NAME="exp_year" TYPE="text" VALUE="$itemyear" SIZE=4,1><BR>
	</td></tr>
<tr><td>Remove this item <INPUT NAME="remove_$count" TYPE="checkbox"></td></tr>
</table><HR><p>
   !;
 	 $count++;
	
  } else {
  $toarchive = $newsitem."|".$urll."|".$itemmonth."-".$itemday."-".$itemyear."|".$imagename."|".$desc."\n";
  push (@archive,$toarchive);
  # $count++;
  print "<P>(News Item $count has expired and has been archived.)<P>\n";
  }
 }
}

close(DBASE);


print qq!
<table border=0 cellspacing=10>
<tr><td><h3>News Item $count</h3></td></tr>
<tr><td>Title: <br><INPUT NAME="news$count" TYPE=text SIZE=48></td> </tr>
<tr><td>Image Name (optional): <br><INPUT NAME="image$count" TYPE=text SIZE=48></td> </tr>
<tr><td>Long Desciption: <BR><TEXTAREA NAME="desc$count" WRAP=physical ROWS=10 
COLS=80></TEXTAREA></td></tr>
<TR><td><br>Page Name:<INPUT NAME="url$count" TYPE="text" SIZE=32,1 ><br>
 Expires: 
<b>Month: </b><select NAME="exp_month$count" SIZE=2 VALUE="">
<option value="01">January
<option value="02">February
<option value="03">March
<option value="04">April
<option value="05">May
<option value="06">June
<option value="07">July
<option value="08">August
<option value="09">September
<option value="10">October
<option value="11">November
<option value="12">December
</select>
<B>Day: </B><SELECT NAME="exp_day$count">
<OPTION>1
<OPTION>2
<OPTION>3
<OPTION>4
<OPTION>5
<OPTION>6
<OPTION>7
<OPTION>8
<OPTION>9
<OPTION>10
<OPTION>11
<OPTION>12
<OPTION>13
<OPTION>14
<OPTION>15
<OPTION>16
<OPTION>17
<OPTION>18
<OPTION>19
<OPTION>20
<OPTION>21
<OPTION>22
<OPTION>23
<OPTION>24
<OPTION>25
<OPTION>26
<OPTION>27
<OPTION>28
<OPTION>29
<OPTION>30
<OPTION>31
</SELECT>
<B>Year:</B> <INPUT NAME="exp_year$count" TYPE="text" VALUE="$year" SIZE=4,1 MAXLENGTH=4>
</td>
</tr></table>
<p>!;

print qq!

<hr><p><INPUT NAME="action" TYPE="submit" VALUE="Update">
</form>

</body>
</html>!;

if (@archive) {
 open(FILE, ">>$archivefile") || print "I can't open $archivefile\n";
 print FILE "@archive";
 close(FILE);
}

}


#########################################
# Update and Display
##########################################

sub update {

#&check;

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

print qq!

<HTML><HEAD>
<title>News Updater Form</title>
</head>
<BODY BGCOLOR="#D2BFD2">
<H1>$sitename Announcement Update Results</H1>

!;

if (-e $headerfile) {
	open(HEADER, "$headerfile") || print "I can't open $headerfile\n";
 	@header = <HEADER>;
	close(HEADER);
}

if (-e $footerfile) {
	open(FOOTER, "$footerfile") || print "I can't open $footerfile\n";
	@footer = <FOOTER>;
	close(FOOTER);
}

open(NEWSFILE, ">$newsfile") || print "I can't open $newsfile\n";


$cnt=0;
foreach $item (@news) {

if ($url[$cnt] && $url[$cnt] !~ /htm/  ) {
  $url[$cnt] = $url[$cnt].".html";
}


if ($item) {
 
 $newsnumber = $cnt+1;
 
 print "<HR><H3>News Item $newsnumber</H3>\n";
 if ($remove =~ /$newsnumber/) { 
    print "News Item $newsnumber removed.<P>\n";
 } else {
   print NEWSFILE $item."|".$url[$cnt]."|".$exp_month[$cnt]."-".$exp_day[$cnt]."-".$exp_year[$cnt]."|".$image[$cnt]."|".$long[$cnt]."\n";
  
   if ($long[$cnt]) {
	$htmlfile = $basepath."/".$url[$cnt];
	open(HTML, ">$htmlfile") || print "I can't open $htmlfile\n";

	print HTML "@header";
      print HTML "<BR><BR><H2>$item</H2><P>\n";
   if ($image[$cnt]) {
      print HTML "<img src=\"$image[$cnt]\" align=left>\n";
   }
	print HTML "<FONT SIZE=+1>$long[$cnt]</FONT><BR><BR>";
	print HTML "@footer";

       close(HTML);
   }

  print "<FONT SIZE=+1><B>Title: </B> $item</FONT><p>\n";
  if ($image[$cnt]) {
   print "<FONT SIZE=+1><B>Image:</b> </font><BR><img src=\"$image[$cnt]\"><p>";
  }
  print "       <FONT SIZE=+1><B>Long Description:</B></font><blockquote>$long[$cnt]</blockquote><B>File 
  name: </B>$url[$cnt]<br><B>Expires:</B> $exp_month[$cnt]/$exp_day[$cnt]/$exp_year[$cnt]<P>";
 }
}
 $cnt++;
}
   
close(NEWSFILE);

print qq!

<A HREF="$scripturl?action=edit">Edit Announcements</A><P>
<A HREF="$homeurl"><FONT SIZE=+1>Go Home</FONT></A></CENTER>

</body></html>!;

}

sub display {

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

$count=1;
open(DBASE, "<$newsfile") || print "I can't open $newsfile\n";
  @news = <DBASE>;
close (DBASE);

$cols = @news;
$width= 600/$cols;

 if ($displaytype eq "table") {
   print "<table width=600 border=0><tr><td colspan=$cols align=center><B><FONT SIZE=+1>$sitename News for $date</FONT></B><BR><BR></td></tr><tr>\n";
 } else {
   print "$sitename News for $date<P><ul>";
 }

foreach $line (@news) { 
	($newsitem,$urll,$exp,$image,$desc) = split(/\|/, $line);
      ($itemmonth,$itemday,$itemyear) = split (/-/,$exp);

  $test="0";
   if ($itemyear > $year){$test="1";}
   if ($itemmonth > $months[$mon] && $itemyear >= $year) {$test="1";}
   if ($itemmonth >= $months[$mon] && $itemyear >= $year && $itemday >= $mday) {$test="1";}      
      
  if ($test eq "1" ) {

   if ($displaytype eq "list") {
     print "<LI><A HREF=\"$baseurl/$urll\"><font>$newsitem</font></A>\n";
      if ($image) {
        print "<br><img src=\"$image\">\n";
      }

   } else {
      print "<td width=$width align=center valign=top><A HREF=\"$baseurl/$urll\">$newsitem</A>";
      if ($image) {
        print "<br><img src=\"$image\">";
      }
      print "</td>\n";
   }	
  } 
 
}
if ($displaytype eq "list") { print "</ul>\n"; }
if ($displaytype eq "table") { print "</tr></table>\n"; }
}


sub check {

	$counter=0;
foreach $item (@news) {

if ($news[$counter]) {

if ($long[$counter] && !$url[$counter]) {
	$err = 'You forgot the page name. We won\'t know how to find your long description!';
&error;
}

if (!$exp_day[$counter] || !$exp_month[$counter]) {
	$err = 'You forgot part of the date!';
&error;
}

$counter++;

}
}

}


sub error($err) {
$err = $_[0];
 print "Content-type: text/html\n\n";
print "<HTML><BODY>";
print $err;
# print "<P>days=@exp_day,months = @exp_month";
print "</body></html>";
exit(0);
}





