#!/usr/bin/perl

# This file takes a comment POST as input, updates 
# comment files and finally the HTML(s)
my $refresh = "src/genroot.pl";

use CGI;
my $cgi = new CGI;

# Make sure that no one is sending malicious file paths here..
if ($cgi->param("src") =~ m/^\// || $cgi->param("src") =~ m/\.\./) {
	die print "Content-type: text/html\n\nPath (" . $cgi->param("src") . ") was rigged, refusing to write";
}

# We find the comments file from a path derived from "src" input
my $filepath = $cgi->param("src")."/comments";
open(COMMENTS, ">>$filepath") or die print "Content-type: text/html\n\nCouldn't open $filepath";

if (-s $filepath > 500000) { 
	die print "Content-type: text/html\n\nComments exceed 500kB, suspecting spam."; 
}

print COMMENTS getDate()." #".getSaneName()." #".getSaneEmail()." #".getSaneComment()." #";

# We refresh the HTMLs and return back to the previous page
system($refresh);
print $cgi->redirect($ENV{HTTP_REFERER});


sub getDate {
	my @timedata = localtime(time);
	return "$timedata[3].".($timedata[4]+1).".".($timedata[5]+1900);
}

sub getSaneName {
	return clean($cgi->param("nick"));
}

sub getSaneEmail {
	return clean($cgi->param("email"));
}

sub getSaneComment {
	return clean($cgi->param("content"));
}

# As you can see, input sanitation is very crude.
# Plx comment if you see something especially worrying.
sub clean {
	return escapeSeparator(escapeAngleBrac($_[0]));
}

sub escapeAngleBrac {
	my $input = $_[0];
	$input =~ s/</&lt;/g;
	$input =~ s/>/&gt;/g;
	return $input;
}

sub escapeSeparator {
	my $input = $_[0];
	$input =~ s/#/\\#/g;
	return $input;
}
