#!/usr/bin/perl

####################################################################
#
#This software is released under the GPL.  Please
#see the included LICENSE file.
#
#Copyright (C) 2001  Michael Spiceland
#Copyright (C) 2001  Jay Kline
#
#This program is free software; you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation; either version 2 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#Use this script at your own risk!  I make no 
#warranties that it is hack proof!
#
#
# This script is part of the Fuzzymonkey Perl Script Archive at
# www.fuzzymonkey.net
#
# Edited by Jay Kline www.slushpupie.com
#
####################################################################


use CGI (-debug);
require "../common.pl";
require "../sitevariables.pl";

############ BEGIN MAIN PROGRAM ################################
$cur = CGI->new();
$mode = "default";
if($cur->param("mode")) {
	$mode = $cur->param("mode");
}
$day = $cur->param("day");
$month = $cur->param("month");
$year = $cur->param("year");


@pretty_months = ("","January","February","March","April","May","June","July","August","September","October","November","December");
$content .= "<br><br><center><font class=default><a href=\"../index.cgi?month=$month&year=$year\">back to calendar</a></font></center>";

if($cur->param("delete")){
	$yearly = $cur->param("yearly");
	$monthly = $cur->param("monthly");
	if($yearly){
		$content .= delete_appointment($day,$month,"*",$cur->param('delete'));
	}elsif($monthly){
		$content .= delete_appointment($day,"*","*",$cur->param('delete'));
	}else{
		$content .= delete_appointment($day,$month,$year,$cur->param('delete'));
	}
}

$content .= print_form();

if($cur->param("day") && $cur->param("month") && $cur->param("year") && $cur->param("info") ){
	$content .= update_day();
}
$content .= display_appointments($day,$month,$year);

$content .= "<br><center><font class=smalltext>Powered by My Calendar $version. Copyright 2002-2006 FuzzyMonkey.net.<br>
Created by the scripting wizards at <a href=http://fuzzymonkey.net>FuzzyMonkey.net</a>.</font></center>";

open (TEMPLATE, "../template.html")||dienice("Content-type: text/html\n\nCould not find template");
while (<TEMPLATE>){
	$page .= $_;
}
$page =~ s/<!-- ?content ?-->/$content/ig;
$page =~ s/<head>/<head>\n<link rel=\"stylesheet\" href=\"$csslink\" type=\"text\/css\">\n/ig;
close (TEMPLATE);
print "Content-type: text/html\n\n$page";
############ BEGIN SUBROUTINES #################################

sub print_form {
	my $return;
	my ($sec,$min,$hr,$mday,$mon,$year_localtime,$wday,$yday,$isdst) = localtime(time());
	my $current_year = $year_localtime + 1900;
	my $current_month = $mon + 1;

	$return .= "
<center>
<form method=post>
<table cellpadding=0 cellspacing=1 border=0 width=375><tr><td>
<table cellpadding=4 cellspacing=0 width=100%>
<tr><td class=emptyday><font class=default>add an event/appointment</font></td></tr>
<tr><td class=emptyday>
<select name=month>";
	for($index=1;$index < 13;$index++){
		if($month){$current_month=$month;}
		if($current_month==$index){
			$return .="<option value=$index selected>$pretty_months[$index]</option>\n";
		}else{
			$return .="<option value=$index>$pretty_months[$index]</option>\n";
		}
	}
	$return .= "
</select>, <select name=day>";
	for($index=1;$index < 32;$index++){
		if($day){$mday=$day;}
		if($index == $mday){
			$return .="<option value=$index selected>$index</option>\n";
		}else{
			$return .="<option value=$index>$index</option>\n";
		}
	}
	$return .= "
</select> &nbsp;&nbsp;&nbsp;&nbsp; <select name=year>";
	if($year){$current_year = $year;}
	for($index=$current_year-5;$index < $current_year+5;$index++){
		if($current_year==$index){
			$return .="<option value=\"$index\" selected>$index</option>\n";
		}else{
			$return .="<option value=$index>$index</option>\n";
		}
	}
	$return .= "
</select>
<br>
<input type=radio name=type value=once checked>one time only<br>
<input type=radio name=type value=monthly>once a month<br>
<input type=radio name=type value=yearly>once a year<br>
<!--<input type=radio name=type value=weekly>every week<br>
<input type=radio name=type value=biweekly>every week<br>-->
appointment info:<br>
<textarea name=info rows=4 cols=40></textarea><br>
<input type=submit value=add>
</td></tr>
</table>
</td></tr></table>
</form>
</center>
";
	return $return;
}


# uses get_appointments to create a hash then parses through it and displays them
# needs day month, then year
sub display_appointments($$$){
	my $return;
	my $day = $_[0];
	my $month = $_[1];
	my $year = $_[2];
	my %apps = get_appointments("../appointments.txt");
	my $appointment_text;
	my $appointments;
	my $appointment;
	my @appointments_array;

	$appointment_text .= "<p><center>
<table cellpadding=0 cellspacing=1 border=0 width=375><tr><td>
<table cellpadding=4 cellspacing=0 width=100%>
	<tr><td colspan=2 class=headercell><font class=default>current events/appointments</font></td></tr>";

	@appointments_array = @{$apps{"$month-$day-$year"}};
	foreach $appointment (@appointments_array){
		$appointment =~ s/"//gi;
	#	($appointment) = /(.{0,5})/; #get only the first 100chars
		$appointment_text .="<tr>
		<td valign=top class=emptyday><form method=post>
		<input type=hidden name=delete value=\"$appointment\">
		<input type=hidden name=day value=\"$day\">
		<input type=hidden name=month value=\"$month\">
		<input type=hidden name=year value=\"$year\">
		<input type=submit value=delete></form></td>
		<td valign=top class=emptyday width=100%>$appointment</td></tr>";
	}

	@appointments_array = @{$apps{"$month-$day-*"}};
	foreach $appointment (@appointments_array){
		$appointment =~ s/"//gi;
	#	($appointment) = /(.{0,5})/; #get only the first 100chars
		$appointment_text .="<tr>
		<td valign=top class=emptyday><form method=post>
		<input type=hidden name=delete value=\"$appointment\">
		<input type=hidden name=day value=\"$day\">
		<input type=hidden name=month value=\"$month\">
		<input type=hidden name=year value=\"$year\">
		<input type=hidden name=yearly value=\"yes\">
		<input type=submit value=delete></form></td>
		<td valign=top class=emptyday width=100%>$appointment</td></tr>";
	}

	@appointments_array = @{$apps{"*-$day-*"}};
	foreach $appointment (@appointments_array){
		$appointment =~ s/"//gi;
	#	($appointment) = /(.{0,5})/; #get only the first 100chars
		$appointment_text .="<tr>
		<td valign=top class=emptyday><form method=post>
		<input type=hidden name=delete value=\"$appointment\">
		<input type=hidden name=day value=\"$day\">
		<input type=hidden name=month value=\"$month\">
		<input type=hidden name=year value=\"$year\">
		<input type=hidden name=monthly value=\"yes\">
		<input type=submit value=delete></form></td>
		<td valign=top class=emptyday width=100%>$appointment</td></tr>";
	}
	
	$appointment_text .= "</table></td></tr></table></center>";
	$return .= $appointment_text;

	return $return;
}

sub update_day{
	my $return;
	my $update_day = $cur->param("day");
	my $update_month= $cur->param("month");
	my $update_year = $cur->param("year");
	#my $update_info = stripBadHtml($cur->param("info"));
	my $update_info = $cur->param("info");
	$update_info =~ s/[\r\f]/<br>/gi;
	$update_info =~ s/[\n]//gi;
	$update_info =~ s/"//gi;
	my $type = $cur->param("type");
	if($type =~ /monthly/){
		$update_month= "*";
		$update_year= "*";
	}
	if($type =~ /yearly/){
		$update_year= "*";
	}

	unless(-e "../appointments.txt"){
		`touch ../appointments.txt`;
		$return .= "Appointments.txt didn't exist: I had to create it.<br>";
	}
	unless(-W "../appointments.txt"){
		dienice("Content-type: text/html\n\n
		<html><body>For some reason I am not able to read the appointments.txt file.  Could you
		please make sure that it exists (in the same folder as index.cgi) and that I have
		the correct permissions to read it?");	
	}

	
	open(OUTFILE,">>../appointments.txt") or $return .= "couldn't open data file: $!!<br>";
	flock(OUTFILE,2);
	print OUTFILE "$update_month-$update_day-$update_year\t$update_info\t0\n";
	flock(OUTFILE,8);
	close(OUTFILE);
	
	return $return;
}

sub delete_appointment($$$$){
	my $day = $_[0];
	my $month = $_[1];
	my $year = $_[2];
	my $done;
	my $appointment_to_delete = $_[3];
	my $return;
	my %apps = get_appointments("../appointments.txt");
	
	if(open(OUTFILE, ">../appointments.txt")){
		foreach $date (sort keys %apps){
			# print "$date has \t", scalar(@{$appointments{$date}})," appointments ";
			foreach $appointment (sort @{$apps{$date}}){
				if( ($appointment eq $appointment_to_delete) && ($date eq "$month-$day-$year") && !$done){
					$done = 1;
				}else{
					print OUTFILE "$date\t$appointment\t0\n";
				}					
			}
		}
		close(OUTFILE);

	}else{
		$return .= "error: $!";
	}
	
	return $return;
}




#####################################################3
#subs from slashdot to remove bad html
#####################################################
# Thanks to Slashdot for these
# Approved HTML tags for HTML posting
@approvedtags = (
        'B','I','P .*','P','A',
        'LI','OL','UL','EM','BR',
        'STRONG','BLOCKQUOTE',
        'HR','DIV .*','DIV','TT'
        );

sub stripBadHtml
{
        my ($str) = @_;

        $str =~ s/(\S{90})/$1 /g;
        $str =~ s/<(?!.*?>)//;
        $str =~ s/<(.*?)>/approvetag($1,@approvedtags)/sge; #replace
tags with approved ones
        return $str;
}

sub approvetag
{
        my ($tag,@apptag) = @_;

        $tag =~ s/^\s*?(.*)\s*?$/$1/e; #trim leading and trailing spaces

        if (uc(substr ($tag, 0, 2)) eq 'A ')
        {
                $tag =~ s/^.*?href="?(.*?)"?$/A HREF="$1"/i; #enforce "s
                return "<" . $tag . ">";
        }

        foreach my $goodtag (@apptag)
        {
                $tag = uc $tag;
                if ($tag eq $goodtag || $tag eq '/' . $goodtag)
                        {return "<" . $tag . ">";}
                #check against my list of tags
        }
        return "";
}

