#!/usr/bin/perl
#
# tropy.cgi - Version 20051105.
#
# Copyright (C) 2005 by Hiroshi Yuki.
# <hyuki@hyuki.com>
# http://www.hyuki.com/tropy/
#
# This program is free software; you can redistribute it and/or
# modify it under the same terms as Perl itself.
#
##############################
package Tropy;
use strict;
use CGI::Carp qw(fatalsToBrowser);
use Digest::MD5 qw(md5_hex);
##############################
# Default dir tree.
##############################
# +--- tropy.cgi
# +--- html
# |    +--- 12345678.html
# |    +--- 31415926.html
# |    +--- ...
# +--- files
#      +--- 12345678.txt
#      +--- 31415926.txt
#      +--- ...
##############################
# Config section.
##############################
my $thisurl_absolute = 'http://roy.orz.hm:8088/tropy-php/';
my $site_name = 'Tropy';
my $dir_html = 'html'; # Directory for Cached HTML files.
my $dir_files = 'files'; # Directory for user-written text files and the index file.
my $file_index = "$dir_files/index.txt";
my $tropy_self = 'tropy.cgi';
##############################
my $sendmail = "";
# $sendmail = "/usr/sbin/sendmail -t -n";
my $adminmail = "";
# $adminmail = 'somebody@example.com';
my $maxidlen = 8;
my $id_pattern = qq([0-9]{$maxidlen});
my $maxlength = 1000;
my $maxlines = 20;
my $maxcols = 80;
my $maxrows = $maxlines;
my $maxtitle = $maxcols - 3;
my $maxpages = 10000;
my $session_digest = md5_hex(join('', values %ENV) . localtime() . ":" . $$);
my $random_seed = hex(substr($session_digest, 0, 8));
my $create_id = substr(sprintf("%0${maxidlen}u", $random_seed), 0, $maxidlen);
my $time_visible_msec = "3000";
my $time_jumpto_sec = "3";
my $content_type = "Content-type: text/html; charset=utf-8\n\n";
my $allow_rebuild = 1;
my $allow_html = 0;
my $show_plink = 1;
##############################
sub main();
sub do_write($);
sub do_edit($);
sub do_create();
sub do_random();
sub print_jumpto($);
sub print_error($);
sub print_header($$);
sub get_header($$$$$$);
sub get_random_id();
sub get_style($);
sub get_subject($);
sub get_navi($$);
sub unlink_html($);
sub build_html($);
sub init_form();
sub escape($);
sub delete_random_page();
sub send_mail($$$$);
sub _make_filename($$);
sub _make_index($);
##############################
my %form;
my %database;
my $main_command;

main();
exit(0);

sub main() {
	# Random init.
	srand($random_seed);
	rand(); rand(); rand();

	init_form();
	if (not tie(%database, 'Tropy', $dir_files, $file_index)) {
		print_error("tie");
	}
	foreach (keys %form) {
		if (/^c$/) {
			$main_command = 'create';
			do_create();
			last;
		} elsif (/^e($id_pattern)$/) {
			$main_command = 'edit';
			do_edit($1);
			last;
		} elsif (/^w($id_pattern)$/) {
			$main_command = 'write';
			do_write($1);
			last;
		} elsif (/^rebuild$/) {
			if ($allow_rebuild) {
				for my $id (keys %database) {
					if ($id =~ /^$id_pattern$/) {
						unlink_html($id);
						build_html($id);
					}
				}
			}
		}
	}
	if (not $main_command) {
		$main_command = 'random';
		do_random();
	}
	untie(%database);
}

sub do_edit($) {
	my ($id) = @_;
	if ($main_command eq 'create' or exists($database{$id})) {
		my $title = $database{$id} ? get_subject($id) : "New Page";
		print_header($id, $title);
		print_editform($id, $database{$id});
		print get_footer();
	} else {
		print_error("edit non id");
	}
}

sub print_editform($$) {
	my ($id, $msg) = @_;
	my $mymsg = escape($msg);
	print <<"EOD";
  <form action="" method="post">
	<input type="hidden" name="w$id" value="1">
	<textarea cols="$maxcols" rows="$maxrows" name="mymsg">$mymsg</textarea><br><input type="submit" value="Write">
  </form>
EOD
}

sub do_write($) {
	my ($id) = @_;
	my $msg = $form{mymsg};
	$msg =~ s/\n+$/\n/;
	my @cr = ($msg =~ /\n/g);

	if ($maxpages < scalar(keys(%database))) {
		delete_random_page();
	}

	if (length($msg) > $maxlength) {
		print_header($id, "length > $maxlength");
		print_editform($id, $msg);
		print get_footer();
	} elsif (@cr >= $maxlines) {
		print_header($id, "lines > $maxlines");
		print_editform($id, $msg);
		print get_footer();
	} else {
		if ($form{mymsg}) {
			$database{$id} = $msg;
			send_mail($id, get_subject($id), 'edit', $msg);
			unlink_html($id);
			build_html($id);
			print_jumpto($id);
		} else {
			send_mail($id, get_subject($id), 'delete', $database{$id});
			delete $database{$id};
			unlink_html($id);
			do_random();
		}
	}
}

sub delete_random_page() {
	my $id = get_random_id();
	delete $database{$id};
	unlink_html($id);
}

sub print_jumpto($) {
	my ($id) = @_;
	my $meta = qq(<meta http-equiv="refresh" content="$time_jumpto_sec; url=${thisurl_absolute}${dir_html}/${id}.html">\n);
	my $navi = qq(<div id="navi"></div>);
	print $content_type;
	print get_header("$site_name...", "", 'black', 'white', $navi, $meta);
	print get_footer();
}

sub print_error($) {
	my ($msg) = @_;
	$msg = escape($msg);
	print_header(undef, '?');
	print qq(<h1>$msg</h1>);
	print get_footer();
	exit(0);
}

sub print_header($$) {
	my ($id, $title) = @_;
	my ($color, $bgcolor) = get_style($id);
	my $navi = get_navi($id, $form{myeditable});
	print $content_type;
	print get_header("$title - $site_name", $title, $color, $bgcolor, $navi, "");
}

sub get_navi($$) {
	my ($id, $editable) = @_;
	my $mod = 17;
	my $random_url = "$tropy_self";
	if ($id % $mod > 0) {
		for (1 .. $mod * 3) {
			my $nextid = get_random_id();
			if (($id + 1) % $mod == $nextid % $mod) {
				# Found.
				$random_url = "$dir_html/$nextid.html";
				last;
			}
		}
	}
	my $edit = $editable ? qq(<a href="$tropy_self?e$id">Edit</a>) : '';
	my $create = qq(<a href="$tropy_self?c">Create</a>);
	my $random = qq(<a href="$random_url">Random</a>);
	my $plink = $show_plink ? qq(<a href="$dir_html/$id.html">Permalink</a>) : '';
	return qq(<p id="navi">$edit $create $random $plink</p>);
}

sub escape($) {
	my ($s) = @_;
	$s =~ s|\&|&amp;|g;
	$s =~ s|<|&lt;|g;
	$s =~ s|>|&gt;|g;
	$s =~ s|"|&quot;|g;
	return $s;
}

sub init_form() {
	my $query;
	if ($ENV{REQUEST_METHOD} =~ /^post$/i) {
		read(STDIN, $query, $ENV{CONTENT_LENGTH});
	} else {
		$query = $ENV{'QUERY_STRING'};
	}
	my @assocarray = split(/&/, $query);
	foreach (@assocarray) {
		my ($property, $value) = split /=/;
		$value =~ tr/+/ /;
		$value =~ s/%([A-Fa-f0-9][A-Fa-f0-9])/pack("C", hex($1))/eg;
		$value =~ s/\r\n/\n/g;
		$form{$property} = $value;
	}
}

sub do_random() {
	my $random_id = get_random_id();
	if ($random_id =~ /^$id_pattern$/) {
		build_html($random_id);
		print_jumpto($random_id);
	} else {
		$main_command = 'create';
		do_create();
	}
}

sub get_random_id() {
	my @id = keys %database;
	return $id[int(rand(@id))];
}

sub unlink_html($) {
	my ($id) = @_;
	unlink("$dir_html/$id.html");
}

sub build_html($) {
	my ($id) = @_;
	my ($color, $bgcolor) = get_style($id);
	my $navi = get_navi($id, 1);

	# Check.
	if (-s("$dir_html/$id.html") > 0) {
		return;
	}

	# Read.
	if (not open(READ, "$dir_files/$id.txt")) {
		print_error("build from $id");
	}
	my $caption = <READ>;
	chomp($caption = escape($caption));
	local $/;
	my $content = <READ>;
	close(READ);
	if (!$allow_html) {
		$content = escape($content);
		$content =~ s(\n\n+)(\n\n)g;
		$content =~ s(\n\n)(</p><p>)g;
		$content =~ s(\n)(<br />)g;
	}

	# Write.
	if (not open(WRITE, "> $dir_html/$id.html")) {
		print_error("build to $id");
	}
	print WRITE get_header("$caption - $site_name", $caption, $color, $bgcolor, $navi, "");
	print WRITE "<p>$content</p>";
	print WRITE get_footer();
	close(WRITE);
}

sub get_header($$$$$$) {
	my ($title, $caption, $color, $bgcolor, $navi, $meta) = @_;
	return <<"EOD";
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html lang="ja">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta http-equiv="content-style-type" content="text/css">
$meta<base href="$thisurl_absolute">
<style type="text/css"><!--
body{font-family:Verdana,sans-serif;margin:2% 20% 10% 20%;color:$color;background-color:$bgcolor;}
input{font-family:Verdana,sans-serif;}
#navi{text-align:right;}
p{line-height:150%;}
a{color:gray;background-color:$bgcolor;text-decoration:none;}
a:hover{text-decoration:underline;color:white;background-color:gray;}
--></style>
<script type="text/javascript">
<!--
function onLoad(){
  document.getElementById("navi").style.visibility="hidden";
  setTimeout("onTimeout()", $time_visible_msec);
}
function onTimeout(){
  document.getElementById("navi").style.visibility="visible";
}
// -->
</script>
<title>$title</title>
</head>
<body onLoad="onLoad()">
$navi<h1>$caption</h1>
EOD
}

sub get_footer() {
	return "</body></html>\n";
}

sub send_mail($$$$) {
	my ($pagename, $subject, $mode, $content) = @_;
	return unless $sendmail;
	my $pages = scalar(keys %database);
	my $message = <<"EOD";
To: $adminmail
From: $adminmail
Subject: [Tropy/$mode] $subject
MIME-Version: 1.0
Content-type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

--------
MODE = $mode
REMOTE_ADDR = $ENV{REMOTE_ADDR}
REMOTE_HOST = $ENV{REMOTE_HOST}
--------
${thisurl_absolute}$pagename.html
--------
$content
--------
pages = $pages
--------
EOD
	open(MAIL, "| $sendmail");
	print MAIL $message;
	close(MAIL);
}

sub get_style($) {
	my ($id) = @_;
	my ($color, $bgcolor) = ('black', 'white');
	if ($main_command ne 'create') {
		my $digest = md5_hex($id);
		my $range = 32;
		my $r = 255 - (hex(substr($digest, 0, 2)) % $range);
		my $g = 255 - (hex(substr($digest, 2, 2)) % $range);
		my $b = 255 - (hex(substr($digest, 4, 2)) % $range);
		$color = 'black';
		$bgcolor = sprintf("#%02X%02X%02X", $r, $g, $b);
	}
	return ($color, $bgcolor);
}

sub do_create() {
	do_edit($create_id);
}

sub get_subject($) {
	my ($id) = @_;
	if ($database{$id} =~ /^(.*)/) {
		my $caption = $1;
		if (length($caption) > $maxtitle) {
			$caption =~ s/^(.{$maxtitle}).*/$1.../;
		}
		return escape($caption);
	} else {
		return "";
	}
}

sub TIEHASH {
	my ($class, $dir, $index) = @_;
	my $self = {
		dir => $dir,
		index => $index,
		id => undef,
		keys => undef,
	};
	bless($self, $class);
	$self->_make_index();
	if (not open(INDEX, $index)) {
		die "tie index";
	}
	my @keys = grep(/^$id_pattern$/, <INDEX>);
	chomp(@keys);
	my %id = map { $_ => 1 } @keys;
	close(INDEX);
	$self->{id} = \%id;
	return $self;
}

sub STORE {
	my ($self, $id, $value) = @_;
	if ($id !~ /^($id_pattern)$/) {
		die "store nonid";
	}

	# Replace file.
	my $filename = $self->_make_filename($id);
	if (not open(FILE, "> $filename")) {
		die "store $id file";
	}
	$value =~ s/\x0D\x0A/\n/g;
	print FILE $value;
	close(FILE);

	# Append $id.
	if (not $self->{id}->{$id}) {
		if (not open(INDEX, ">> $self->{index}")) {
			die "store index";
		}
		print INDEX "$id\n";
		close(INDEX);
		$self->{id}->{$id} = 1;
	}

	return $value;
}

sub FETCH {
	my ($self, $key) = @_;
	my $filename = $self->_make_filename($key);
	open(FILE, $filename) or return(undef);
	local $/;
	my $value = <FILE>;
	close(FILE);
	return $value;
}

sub DELETE {
	my ($self, $key) = @_;
	my $filename = $self->_make_filename($key);
	unlink($filename);
	delete $self->{id}->{$key};

	# Write index.
	my @id = keys %{$self->{id}};
	if (not open(INDEX, "> $self->{index}")) {
		die "delete index";
	}
	if (@id) {
		print INDEX join("\n", @id), "\n";
	}
	close(INDEX);
}

sub FIRSTKEY {
	my ($self) = @_;
	@{$self->{keys}} = keys %{$self->{id}};
	return shift @{$self->{keys}};
}

sub NEXTKEY {
	my ($self) = @_;
	return shift @{$self->{keys}};
}

sub EXISTS {
	my ($self, $key) = @_;
	my $filename = $self->_make_filename($key);
	return -s($filename);
}

sub _make_filename($$) {
	my ($self, $key) = @_;
	return $self->{dir} . "/$key.txt";
}

sub _make_index($) {
	# if (-s($file_index) > 0 and -M($file_index) < 1.0) {
	if (-s($file_index)) {
		return;
	}
	if (not opendir(DIR, $dir_files)) {
		print_error("build index dir");
	}
	my @index;
	my $entry;
	while ($entry = readdir(DIR)) {
		if ($entry =~ /^($id_pattern)\.txt$/) {
			my $id = $1;
			if (-s("$dir_files/$id.txt") > 0) {
				push(@index, $id);
			}
		}
	}
	close(DIR);
	if (not open(INDEX, "> $file_index")) {
		print_error("build index open");
	}
	if (@index) {
		print INDEX join("\n", @index), "\n";
	}
	close(INDEX);
}

1;
__END__
