#!/usr/local/bin/perl

#----------------------- environment settings -----------------------
$method=$ENV{'REQUEST_METHOD'};
$script_name=$ENV{'SCRIPT_NAME'};

$mailprog = '/usr/lib/sendmail';
$my_email = 'webmaster@nthucad.cs.nthu.edu.tw';
$my_name = 'Alex C.-Y.Chang';
$mailMe = 1; # Send me an email when new entry arrives

$document_root="/raid/web/";
$reg_file="/guestbook.htm";
$full_reg=$document_root.$reg_file;
$thank_url="http://nthucad.cs.nthu.edu.tw/guestbook.htm";
$numberfile="/raid/web/message/number.txt";  
$pagedir="/raid/web/message/";  
$pageurl="http://nthucad.cs.nthu.edu.tw/message/";
$limit="29";  

#-------------------------- main program ----------------------------

if ($method eq "POST") {

	read(STDIN,$data_string,$ENV{'CONTENT_LENGTH'});
	@data_array=split(/&/,$data_string);   
	foreach (@data_array) {
	($key,$value)=split(/=/,$_);		
       $value =~ tr/+/ /;
       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
       $value =~ s/<!--(.|\n)*-->//g;
    
       if ($key eq 'comment') {
                $value =~ s/\cM//g;
              $value =~ s/\n\n/<p>/g;
              $value =~ s/\n/<br>/g;
              $value =~ s/&lt;/</g;
              $value =~ s/&gt;/>/g;
              $value =~ s/&quot;/"/g;
              $value="<BLOCKQUOTE>$value</BLOCKQUOTE>";
        }

		$parsed_data{$key}=$value;   		

	}
	&update_regfile($full_reg,$parsed_data{'name'},$parsed_data{'email'},$parsed_data{'title'},$parsed_data{'comment'});
        if ($mailMe) { &mailMe; }               

	print "Location: $thank_url\n\n";
	
} else {
	&html_header("Error","Server Error");
	print"<p>Server uses unsupported method\n";
}
#---------------------------- sub programs ----------------------------


sub html_header {
	
	($title,$headline)=@_;
	if (!$headline) {
	   $headline=$title; 
	}
	print "Content-type: text/html\n\n";
	print "<html>\n";
	print "<head><title>$title</title></head>\n";
	print "<body>\n";
	print "<h1>$headline</h1>\n";
	print "<hr>\n";
}
sub update_regfile {

	($filename,$name,$email,$title,$comment)=@_; 

	$reg_time=`date +'%r, %a, %h/%d/%y'`; 
	chop($reg_time);
	#####################################
	open (NUMBER,"<$numberfile") || Die ("File number.txt cannot open!"); 
	$nlines = <NUMBER>;
	chop($nlines); 
	@nlines = split(/#/,$nlines);   
	$number = $nlines[0];  
	$page = $nlines[1];
	close (NUMBER);
	##########################################
	$flag=0;  
       
	open (FILE,"<$filename") || Die ("Can't Open $filename: $!\n");
	@lines = <FILE>;   
	close (FILE);

	$size = @lines;  
	open (REGFILE,">$filename") || Die ("Can't Open $filename: $!\n");
	flock(REGFILE,2);

	if ($number > $limit) {
	#---寫出超過篇數的留言###################3
		open (OUT,">$pagedir$page.htm")||Die("File outpage.htm cannot open!\n");   
		print OUT (@lines);
		close (OUT); 
	#--寫出目前的留言#####################
	 	for ( $i=0 ; $i<=$size ; $i++){
		    $_=$lines[$i];

		    if ( ($_ =~ /<!--begin-->/) || ($size== 0)){
                        $flag=1;
			#################if <!---begin-->
			print REGFILE "<!--begin-->\n";
			print REGFILE "<tr><td>&nbsp;&nbsp;&nbsp;\n";
			if ($email){
				print REGFILE "姓名:<a href=\"mailto:$email\"><font color=blue>$name</a></font>&nbsp;&nbsp;&nbsp;&nbsp;\n";
			}else {
				print REGFILE "姓名:<font color=blue>$name</font>&nbsp;&nbsp;&nbsp;\n";
			}
			print REGFILE "主題：<font color=\"#808000\">$title</font><br>\n";
			print REGFILE "&nbsp;&nbsp;&nbsp;留言時刻：&nbsp;&nbsp;<fontcolor=\"#808000\">$reg_time</font><br>\n";
			print REGFILE "&nbsp;&nbsp;&nbsp;留言內容:<br><br>\n";

			print REGFILE "<font color=2f4f4f><b>$comment</b></font><hr width=90%></td></tr>\n\n";
		    }
		    elsif ($_ =~ /<!--oldmessage-->/){
			print REGFILE "<!--oldmessage--><a name=\"oldmessage\"><center>\n";   
			print REGFILE "<a href=\"$pageurl$page.htm\">$page</a>\n";   
		    }
                    elsif ($_ =~/<!--end-->/){
                        print REGFILE "<!--end-->\n";
			$flag=0;
		    }
		    else{ if ($flag==0){ 
		        	print REGFILE $_; }
                    }
		}
		 flock(REGFILE,8); 
		 close(REGFILE);
	#######message數歸零, page加一#################
		open (NUMBER,">$numberfile")|| Die ("number file can't open!\n");  
		flock(NUMBER,2); 
		$number = 1;
		$page++;   
	        print NUMBER ("$number#$page\n");   
		flock(NUMBER,8); 
		close(NUMBER);  
	#######  加入留言#############################3

	} else {
		for ( $i=0 ; $i<=$size ; $i++){
		 $_=$lines[$i];
		 if ( ($_ =~ /<!--begin-->/) || ($size== 0)){
			print REGFILE "<!--begin-->\n";
			print REGFILE "<tr><td>&nbsp;&nbsp;&nbsp;\n";
			if ($email){
				print REGFILE "姓名:<a href=\"mailto:$email\"><font color=blue>$name</a></font>&nbsp;&nbsp;&nbsp;&nbsp;\n";
			}else {
				print REGFILE "姓名:<font color=blue>$name</font>&nbsp;&nbsp;\n";
			}
			print REGFILE "主題：<font color=\"#808000\">$title</font><br>\n";
			print REGFILE "&nbsp;&nbsp;&nbsp;留言時刻：&nbsp;&nbsp;<font color=\"#808000\">$reg_time</font><br>\n";
			print REGFILE "&nbsp;&nbsp;&nbsp;留言內容:<br><br>\n";

			print REGFILE "<font color=2f4f4f><b>$comment</b></font><hr width=90%></td></tr>\n\n";		  }    
		 else {
			print REGFILE $_; 
		  }
		}###for
		 flock(REGFILE,8); 
		 close(REGFILE);
	################# message number plus one
		open (NUMBER,">$numberfile") || Die ("number file can't opened!\n");   
		$number++;
	        print NUMBER ("$number#$page\n");   
		close(NUMBER); 
	}
}	
sub mailMe {
      open (MAIL, "|$mailprog -t");
                                                                                
      print MAIL "To: $my_email\n";
      print MAIL "From: guestbook\n";
      print MAIL "Subject: 有人在NTHUCAD留言囉~~~\n\n";
      print MAIL "$name 留言\n";
      print MAIL "內容:$comment";
      close (MAIL);
}
