#!/usr/bin/perl

##########################################################################
# import.cgi - My Calendar importing script
#
# Copyright 2003 by Michael Spiceland of Fuzzymonkey.org
#
##########################################################################

use CGI;

$cur = CGI->new();
$content = "";

$mode = $cur->param('mode');
if($mode eq "import"){
	$content .= upload();
	unless($content =~ /not uploaded/i){
		$content .= import_calendar();
	}
}else{
	$content .= print_upload_form();
}

open (TEMPLATE, "../template.html")||dienice("Content-type: text/html\n\nCould not find template");
while (<TEMPLATE>){
	$page .= $_;
}
$page =~ s/<!-- ?content ?-->/$content/ig;
close (TEMPLATE);
printpage($page);


##########################################################################
# subroutines
##########################################################################
sub print_upload_form{
	my $return;

	$return .= "<table width=500><tr><td>";
	$return .= "<p align=center><b>Import Outlook Exported .csv file</b></p>";
	$return .= "<p>In Outlook go to Export/Import and choose to export to a file.  Export your calendar
	entries to a comma separated file or .csv file.  After saving the file to your harddisk,
	you may now hit the browse button to upload and import
	it into your web calendar.</b></p>";
	$return .= "
	<form method=post ENCTYPE=\"multipart/form-data\">
	<input type=hidden name=mode value=import>
	<input type=\"file\" name=\"FILE1\"><br>
	<!-- <input type=\"checkbox\" name=snyc>sync appointments *<br> -->
	<input type=\"submit\" value=\"Import File\"><br>
	<!-- <small>* Checking the box to sync your appointments will delete any previously added Outlook
	appointments that are not included in this Import.  Otherwise they would be added regardless.</small>-->

	</form>";
	$return .= "</td></tr></table>";

	return $return;
}

sub upload {
	my $return;	

	$onnum = 1;
	while ($onnum != 11) {
		my $file = $cur->param("FILE$onnum");
		if ($file ne "") {
			my $fileName = $file; 
			$fileName =~ s!^.*(\\|\/)!!; 
			$newmain = $fileName;
			if (($fileName =~ /\.csv$/i)) { 
				open (OUTFILE, ">outlook.csv"); 
				#$return .= "<font color=green>Uploaded file : $fileName</font><br>";
				while (my $bytesread = read($file, my $buffer, 1024)) { 
					binmode OUTFILE;
					print OUTFILE $buffer; 
				} 
				close (OUTFILE); 
			}else{
				$return .= "<font color=red>$fileName was not uploaded.  Only .csv files allowed.</font><br>";
			}
		}
		$onnum++;
	}

	return $return;
}


sub import_calendar{
	my $return;

	# open the .csv file that was exported by the calendar program
	open(IMPORT_FILE,"<outlook.csv") || dienice("Could not open file to import! $!\n");
	flock(2,IMPORT_FILE);

	# now that we know we have a file to open, lets remove any older outlook appointments
	if(-e "../appointments-imported.txt"){
		unlink("../appointments-imported.txt");
	}
	
	open(APPOINTMENTS_OUTLOOK,">>../appointments-imported.txt") || dienice("Could not open appointments-imported.txt file
		to store imported files to! $!\n");
	flock(2,APPOINTMENTS_OUTLOOK);



	#look at the first line and try to interpret where the stuff goes
	@headings = split(/,/,<IMPORT_FILE>);
	$no_headings = @headings;
	$count =0;
	$found =0;
	$count_added=0;
	foreach $heading (@headings){
		chomp($heading);
		$heading =~ s/"//gi;
		#$return .= "$heading - $count\n";
		if($heading =~ /subject/i){$col_subject = $count;$found++;}
		if($heading =~ /start date/i){$col_start_date = $count;$found++;}
		if($heading =~ /end date/i){$col_end_date= $count;$found++;}
		if($heading =~ /start time/i){$col_start_time= $count;}
		if($heading =~ /end time/i){$col_end_time= $count;}
		if($heading =~ /all day event/i){$col_all_day= $count;}
		$count++;
	}
	
	#only calculate this stuff if we have succesfully recognized the file
	if($found >2){
		$line = 1;
		$partial = "";
		while(<IMPORT_FILE>){
			$line++;
			#$return .= $_;
			chomp;
			$_ =~ s/([^",]),([^",])/$1$2/g; # get rid of unnecessary commas
			$_ =~ s/,$/$1$2/g; # get rid of unnecessary commas
			$_ =~ s/"//g;
			@columns = split(/,/,$_);
			$no_columns = @columns;
			#$return .= "$no_columns from $_\n";
			if($no_columns == $no_headings){
				$return .= create_appointments();
				$count_added++;
			}else{
				#$return .= "line $line: $_ didn't match\n";
				$partial .= $_;
				#$return .= "adding $_ to partial.\n";
			}
	
			# now the hard part.  We have to combine multiple lines
			# that aren't complete themeselves
			# check partial to see if we have an entire row yet
			@columns = split(/,/,$partial);
			$no_columns = @columns;
			if($no_columns == $no_headings){
				$return .= create_appointments();
				$count_added++;
				#$return .= "$partial is now complete.\n";
				$partial = "";
			}else{
				#$return .= "$partial is not yet complete because only $no_columns columns.\n";
			}
		}
	}
	flock(8,IMPORT_FILE);
	close(IMPORT_FILE);	

	$return .= "$count_added appointments imported.<br>";
	$return .= "<p><a href=\"../index.cgi\">back to calendar</a></p>";

	return $return;
}

sub create_appointments(){
	my $return;

	my $appointment = $columns[$col_subject];
	my $start_date = $columns[$col_start_date];
	my $end_date = $columns[$col_end_date];
	my $start_time = $columns[$col_start_time];
	my $end_time = $columns[$col_end_time];
	my $all_day = $columns[$col_all_day];
	
	if(($start_date eq $end_date) && ($all_day =~ /false/i)){$appointment .= " ($start_time)";}

	my ($month_start,$day_start,$year_start) = split(/\//,$start_date);
	my ($month_end,$day_end,$year_end) = split(/\//,$end_date);

	while(($year_start-1) < $year_end){
		#$return .= "processing year $year_start\n";
		while(($month_start-1) < $month_end){
			#$return .= "processing month $month_start\n";
			while(($day_start-1) < $day_end){
				#$return .= "processing day $day_start\n";
				unless(($all_day =~ /true/i) && ($day_start eq $day_end)){
					#$return .= "$month_start-$day_start-$year_start\t$appointment\t0\n<br>";
					print APPOINTMENTS_OUTLOOK "$month_start-$day_start-$year_start\t$appointment\t0\n";
				}
				$day_start++;
			}
			$month_start++;
		}
		$year_start++;
	}
	return $return;
}
sub printpage($){
	print "Content-type: text/html\n\n
	$_[0]\n";
}
sub dienice($){
	printpage($_[0]);
	exit(3);
}

