#!/usr/bin/perl
use Socket;
# --------------------------------------------------------  PerlInterpreter
# PerlInterpreter must be the first line of the file.
#
# Copyright (c) 1995, Cunningham & Cunningham, Inc.
#
# This program has been generated by the HyperPerl
# generator.  The source hypertext can be found
# at http://c2.com/cgi/wikibase.  This program belongs
# to Cunningham & Cunningham, Inc., is to be used
# only by agreement with the owner, and then only
# with the understanding that the owner cannot be
# responsible for any behaviour of the program or
# any damages that it may cause.
# --------------------------------------------------------  InitialComments
# This is yet another a WikiClone that uses plain files
# instead of dbm, and uses RCS for version management.
# The goal was to have the simplest possible hack of
# WikiAsStraightPerl that gets around problems with dbm.
# -- OscarNierstrasz
# --------------------------------------------------------  CloneComments
# Various updates to use as wiki for curta.org:
# Tables.  Looser WikiWord syntax.
# Add a textbox to confirm edits to prevent spamming.
# Added rel='nofollow' for http://www.google.com/googleblog/2005/01/preventing-comment-spam.html
# -- LeighKlotz
# --------------------------------------------------------  CloneComments
# ToDo:
# - access old versions
# --------------------------------------------------------  ToDo
# $Log: rcswiki.cgi,v $
# Revision 1.16  2006/07/18 23:24:04  klotz
# *** empty log message ***
#
# Revision 1.15  2004/11/30 05:39:46  klotz
# *** empty log message ***
#
# Revision 1.14  2004/10/29 20:56:10  klotz
# *** empty log message ***
#
# Revision 1.13  2001/02/26 05:50:20  klotz
# COMMENTS
#
# Revision 1.12  2001/02/26 05:47:16  klotz
# various updates and consolidatations
#
# Revision 1.11  2001/02/26 03:12:38  klotz
# search results use / instead of ? because of our apache rewrite rule
#
# Revision 1.10  2001/02/26 02:30:32  klotz
# allow numbers in wiki words
#
# Revision 1.9  2001/02/26 02:16:52  klotz
# remove space
#
# Revision 1.8  2001/02/26 02:13:11  klotz
# simpler
#
# Revision 1.7  2001/02/26 02:12:14  klotz
# simpler
#
# Revision 1.6  2001/02/26 00:11:41  klotz
# tuning
#
# Revision 1.5  2001/02/26 00:11:06  klotz
# dot
#
# Revision 1.4  2001/02/26 00:10:29  klotz
# be more explicit
#
# Revision 1.3  2001/02/26 00:09:28  klotz
# Be more polite
#
# Revision 1.2  2001/02/25 01:12:53  klotz
# first stab at moving to curta.org
#
# Revision 1.1  2001/02/25 01:11:02  klotz
# Initial revision
#
# Revision 1.5  2000/11/29 02:09:02  klotz
# allow GraphicViewII as a link.
#
# Revision 1.4  2000/11/29 02:08:24  klotz
# add AsLink image types png/jpg
#
# Revision 1.3  2000/11/29 02:07:26  klotz
# add inline images
#
# Revision 1.2  2000/11/21 08:15:35  klotz
# update for www
#
# Revision 1.1  2000/11/21 08:14:32  klotz
# Initial revision
#
# Revision 1.4  1999/11/15 11:48:15  oscar
# Fixed bug with HandlePost (first update was always ignored).
# [Thanks to Mark Skipper <mcs@bcs.org.uk>!]
# Added $ThanksMsg flag to optionally print thanks message
# when pages are updated.
#
# Revision 1.3  1999/03/30  12:49:55  oscar
# Email notification of changes by MatthiasRieger
#
# Revision 1.2  1998/10/26  15:13:48  oscar
# Removed references to "copy" field.
# (Redundant with RCS support.)
#
# Revision 1.1  1998/10/09  12:41:17  oscar
# Moved configuration variables to top of script
# Added BootStrap routine to bootstrap from existing dbm files
# Added LockPage and UnlockPage to lock individual files
# Remove RequestLock and ReleaseLock (which lock the whole DB)
# Fixed WritePage to return ci diagnostics
#
# Revision 1.0  1998/10/09  09:49:55  oscar
# First working version.
# See ToDo list for unfinished business.
#
# --------------------------------------------------------  RcsLog

#$RcsBin = "/opt/local/GNU/bin";
$RcsBin = "/usr/bin";
# --------------------------------------------------------  RcsBin

@path = split('/', "$ENV{SCRIPT_NAME}");
$ScriptName = pop(@path);
# --------------------------------------------------------  ScriptName

#$DataBase = "/home/scg/Working/Wiki/$ScriptName";
$DataBase = "/home/curta/wiki";
# --------------------------------------------------------  DataBase

#DefaultTitle = Front . Page;
#DefaultTitle = Software . Composition . Wiki;
$DefaultTitle = Curta . Wiki;
# --------------------------------------------------------  DefaultTitle

$LogoUrl = 'https://curta.org/curta-1-icon.gif';
# --------------------------------------------------------  LogoUrl

# $Background="http://graflex.org/images/leftgray.gif";
$Background = "";
# --------------------------------------------------------  Background
 
$TextColor = "#000000";
# --------------------------------------------------------  TextColor

$LinkColor="#F6A83C";
# --------------------------------------------------------  LinkColor

$VLinkColor="#F6A83C";
# --------------------------------------------------------  VLinkColor

$ALinkColor="#FF0000";
# --------------------------------------------------------  ALinkColor

#ScriptUrl = "http://www.iam.unibe.ch/~scg/cgi-bin/$ScriptName";
$ScriptUrl = "https://curta.org/wiki";
# --------------------------------------------------------  ScriptUrl

$PageTrailer = "Brought to you by <a href='/'>Curta.org</a>";
# --------------------------------------------------------  PageTrailer

#$LogoImage = "<img width=100 src=\"$LogoUrl\">";
$LogoImage = "<a href=$ScriptUrl><img border='0' src=\"$LogoUrl\"></a>";
# --------------------------------------------------------  LogoImage

# Give thanks in HandlePost in response to an edit.
$ThanksMsg = 1;
# --------------------------------------------------------  ThanksMsg

# If this is an email adress, mails are sent
# to this person in case a page changes
#$AdminEmail = 'oscar\@iam.unibe.ch';
# --------------------------------------------------------  AdminEmail

sub AbortScript {
local ($msg) = @_;
print <<EOF ;
<h3>The Wiki Wiki Server Can\'t Process Your Request</h3>
$msg<p>
This information has been logged.<br>
We are sorry for any inconvenience.
EOF
die $msg;
}
# --------------------------------------------------------  AbortScript

sub LoginMessage {
local ($title) = @_;
print <<EOF ;

<h3>Please log in before editing Curta.org Wiki pages</h3>
<p>If you are a registered user at the Curta.org bulletin board, please <a target="new" href="https://curta.org/phpBB2/login.php">log in</a> now and then close the window; you will be returned to this page.</p>
<p>If you are not a registered user, please <a href="https://curta.org/phpBB2/">register</a> first.  Your membership should be approved in a day or so.</p>
<p>After logging in, return to <a href=\"$ScriptUrl\?edit=$title\">this page</a> to edit.</p>
EOF
}
# --------------------------------------------------------  AbortScript

$linkWord = "[A-Z][a-z0-9]+[A-Z]*";
$LinkPattern = "($linkWord){2,}";
# --------------------------------------------------------  LinkPattern

$DefaultRequest = browse;
# --------------------------------------------------------  DefaultRequest

$dobase = 0;
# --------------------------------------------------------  dobase
if ($ENV{REQUEST_METHOD} eq GET){
$RawInput = $ENV{QUERY_STRING};
if (! $RawInput) {
my $pinfo = $ENV{PATH_INFO};
if ($pinfo) {
$dobase=1;
$pinfo =~ s@^/@@;
$pinfo =~ s@\.htm(l)?$@@;
$RawInput = $pinfo;
}
}
}
$RawInput = $DefaultTitle if (! $RawInput);
$RawInput =~ s/^($LinkPattern)/$DefaultRequest=$1/;
if ($ENV{REQUEST_METHOD} eq POST){
read(STDIN, $RawInput, $ENV{CONTENT_LENGTH});
}
#print STDERR "Read $RawInput\n";
# --------------------------------------------------------  RawInput

$FieldSeparator = "\263";
# --------------------------------------------------------  FieldSeparator

$RawInput =~ s/\+/ /g;
foreach $_ (split(/&/, $RawInput)) {
s/\%(..)/pack(C, hex($1))/ge;
s/$FieldSeparator//go;
($_, $CookedInput) = split (/=/, $_, 2);
$CookedInput{$_} = $CookedInput;
}
# --------------------------------------------------------  CookedInput

sub RetrievePage {
local($title) = pop(@_);
if (&PageExists($title))
{open (TITLE,"$DataBase/$title.wiki") || &AbortScript("Can't open $title: $!");}
else { 
local($newPage) = "text${FieldSeparator}Describe $title here.";
return split($FieldSeparator,$newPage); 
}
local($/);
$contents = <TITLE>;
return split($FieldSeparator,$contents);
}
# --------------------------------------------------------  RetrievePage

sub EscapeMetaCharacters {
s/&/&amp;/g;
s/</&lt;/g;
s/>/&gt;/g;
}
# -------------------------------------------------------  EscapeMetaCharacters
# http://www.google.com/googleblog/2005/01/preventing-comment-spam.html
sub InPlaceUrl {
local($num) = (@_);
local($ref) = $InPlaceUrl[$num];
if ($ref =~ m/\.jpg$\|\.gif$\|\.png$/) {
    return "<img src=\"$ref\">";
} else {
    return "<a rel='nofollow' href=\"$ref\">$ref</a>";
}
}
# --------------------------------------------------------  InPlaceUrl

# --------------------------------------------------------  UserId
sub UserId() {
local($uid) = (@_);
return "<a href='https://curta.org/phpBB2/profile.php?mode=viewprofile\&amp;u=$uid'>User $uid</a>";
}

$TranslationToken = $FieldSeparator;
# --------------------------------------------------------  TranslationToken

sub EmitCode {
($code, $depth) = @_;
while (@code > $depth)
{local($_) = pop @code;
print "</$_>\n"}
while (@code < $depth)
{push (@code, ($code));
print "<$code>\n"}
if ($code[$#code] ne $code)
{print "</$code[$#code]><$code>\n";
$code[$#code] = $code;}
}
# --------------------------------------------------------  EmitCode

sub PageExists {
local($title) = pop(@_);
return -f "$DataBase/$title.wiki";
}
# --------------------------------------------------------  PageExists

sub AsAnchor {
local($title) = pop(@_);
&PageExists($title)
? "<a href=\"$ScriptUrl/$title\">$title<\/a>"
: "$title<a href=\"$ScriptUrl\?edit=$title\">?<\/a>";
}
# --------------------------------------------------------  AsAnchor
# http://www.google.com/googleblog/2005/01/preventing-comment-spam.html
sub AsLink {
local($num) = (@_);
local($ref) = $old{"r$num"};
defined $ref
? ($ref =~ /\.gif$\|\.png$\|\.jpg$/
? "<img src=\"$ref\">"
: "<a rel='nofollow' href=\"$ref\">[$num]<\/a>")
: "[$num]";
}
# --------------------------------------------------------  AsLink

$SearchForm = <<EOF ;
<form>
<input
type="text"
size="40"
name="search"
value="$CookedInput{value}">
<\/form>
EOF
# --------------------------------------------------------  SearchForm

sub PrintBodyText {
s/\\\n/ /g;
foreach (split(/\n/, $_)){
$InPlaceUrl=0;
while (s/\b((http)|(ftp)|(mailto)|(news)|(file)|(gopher)):[^\s\<\>\[\]"'\(\)]*[^\s\<\>\[\]"'\(\)\,\.\?]/$TranslationToken$InPlaceUrl$TranslationToken/) { #'
$InPlaceUrl[$InPlaceUrl++] = $&
}
&ProcessTableText();
$code = "";
s/^\s*$/<p>/                  && ($code = '...');
s/^(\t+)(.+):\t/<dt>$2<dd>/   && &EmitCode(DL, length $1);
s/^(\t+)\*/<li>/              && &EmitCode(UL, length $1);
s/^(\t+)\d+\.?/<li>/          && &EmitCode(OL, length $1);
/^\s/                        && &EmitCode(PRE, 1);
$code                         || &EmitCode("", 0);
s/'{3}(.*?)'{3}/<strong>$1<\/strong>/g;
s/'{2}(.*?)'{2}/<em>$1<\/em>/g;
s/^-----*/<hr>/;
s/\b$LinkPattern\b/&AsAnchor($&)/geo;
s/\[(\d+)\]/&AsLink($1)/geo;
s/$TranslationToken(\d+)$TranslationToken/&InPlaceUrl($1)/geo;
s/\[Search\]/$SearchForm/;
s/\[User:(\d+)\]/&UserId($1)/geo;
print "$_\n";
}
&EmitCode("", 0);
if ($intable) {
print "</table>";
$intable = 0;
}
}
# --------------------------------------------------------  PrintBodyText

sub ProcessTableText {
    s///;
    if (! $intable) {
	if (m,^ *\|.*\|$,) {
	    $intable = 1;
	    s,^ *\|,<table border="1"><tr><td>,;
	    s,\|$,</td></tr>,;
	    s,\|,</td><td>,g;
	}
    } else {
	if (m,^ *\|.*\|$,) {
	    s,^ *\|,<tr><td>,;
	    s,\|$,</td></tr>,;
	    s,\|,</td><td>,g;  
	} else {
	    s,^,</table>,;
	    $intable=0;
	}
    }
}
# --------------------------------------------------------  ProcessTableText
sub HandleBrowse {
local($disallowedit) = pop(@_);
$title = $CookedInput{browse};
my $h1 = $title;
$h1 =~ s/([a-z])([A-Z])/\1 \2/go/
print <<EOF ;
<head>
<title>$title</title>
EOF
print "<base href=\"$ScriptUrl/$title\">\n" if ($dobase);
print <<EOF ;
</head>
<body bgcolor="white" background='$Background' text='$TextColor' link='$LinkColor' vlink=$VLinkColor alink='$ALinkColor'>
<h1>$LogoImage <a href="$ScriptUrl\?search=$title">$h1<\/a><\/h1>
EOF
%old = &RetrievePage($title);
$_ = $old{text};
&EscapeMetaCharacters;
&PrintBodyText;
if (! $disallowedit) {
print <<EOF ;
<hr>
<a href="$ScriptUrl\?edit=$title">Edit Text<\/a> of this page
(last edited $old{date} by $old{host})<br>
<a href="$ScriptUrl\?FindPage&value=$title">Find Page<\/a> by browsing or searching<br>
EOF
}
print $PageTrailer if ($PageTrailer);
print "</body>\n";
}
# --------------------------------------------------------  HandleBrowse

sub HandleEdit {
$title = $CookedInput{edit};
$title =~ /^$LinkPattern$/ || &AbortScript("edit: improper name: $title");
%old = &RetrievePage($title);
$_ = $old{text};
s/\r\n/\n/g;
&EscapeMetaCharacters;
$convert = "checked" if $ENV{HTTP_USER_AGENT} =~ /WebExplorer/;
print <<EOF ;
<head>
<title>Edit $title</title>
<style type="text/css">
    div.showme { display: none; }
</style>
</head>
<body bgcolor="white" background='$Background'>
<form method="POST" action="$ScriptUrl">
<h1>$title
<input type="submit" value="Save">
<input type="reset" value="Reset">
</h1>
<textarea name="text" rows='25' cols='75' wrap='virtual'>$_</textarea><br />
<!--<b>IMPORTANT: Explain your changes to this page here:</b> <input type="text" name="currency" value="No good reason"><br />-->
<!--<div class="showme"><input type="checkbox" name="sessionID" value="true"><i >Check this box to xqpstlfk.</i><br /></div>-->
<input type="checkbox" name="convert" value="tabs" $convert>
I can\'t type tabs.
Please <a href="$ScriptUrl?ConvertSpacesToTabs">ConvertSpacesToTabs</a>
for me when I save.<p>
<a href="$ScriptUrl?GoodStyle">GoodStyle</a> tips for editing.<br>
<a href="$ScriptUrl?links=$title">EditLinks</a> to other web servers.<br>
EOF
print <<EOF ;
<input type="hidden" size=1 name="post" value="$title">
</form>
</body>
EOF
}
# --------------------------------------------------------  HandleEdit

sub HandleLinks {
$title = $CookedInput{links};
$title =~ /^$LinkPattern$/ || &AbortScript("link: improper name: $title");
%old = &RetrievePage($title);
print <<EOF ;
<head><title>$title Links</title></head>
<body bgcolor="white" background='$Background'><form method="POST" action="$ScriptUrl">
<h1>$title Links
<input type="submit" value="Save">
<input type="reset" value="Reset"></h1>
[1] <input type="text" size='55' name="r1" value="$old{r1}"><br>
[2] <input type="text" size='55' name="r2" value="$old{r2}"><br>
[3] <input type="text" size='55' name="r3" value="$old{r3}"><br>
[4] <input type="text" size='55' name="r4" value="$old{r4}"><p>
Type the full URL (http:// ...) for each [#] reference cited in the text.<p>
<!--<b>IMPORTANT: Explain your changes to this page here:</b> <input type="text" name="currency" value="No good reason"><br />-->
<!--<div class="showme"><input type="checkbox" name="sessionID" value="true"><i >Check this box to xqpstlfk.</i><br /></div>-->
<input type="hidden" size='1' name="post" value="$title"></form>
EOF
}
# --------------------------------------------------------  HandleLinks

sub HandleSearch  {
local($m, $n, @rec);
$pat = $CookedInput{search};
$pat =~ s/[+?.*()[\]{}|\\]/\\$&/g;
$results = Results;
$results = "for $&" if $pat =~ /\W+/;
print "<head><title>Search $results</title></head>\n";
print "<body bgcolor='white' background='$Background'><h1>$LogoImage Search Results</h1>\n";
opendir(DIR, $DataBase) || &AbortSript("can't opendir $DataBase: $!");
@pages = grep { /\.wiki$/ && -f "$DataBase/$_" } readdir(DIR);
closedir DIR;
foreach $key (@pages) {
$key =~ s/\.wiki$//;
$n++;
%rec = &RetrievePage($key);
if ($key =~/\b\w*($pat)\w*\b/i ||
$rec{text} =~ /\b\w*($pat)\w*\b/i){
$m++;
#print "<a href=\"$ScriptUrl\?$key\">$key<\/a> . . . . . .  $&<br>\n";
print "<a href=\"$ScriptUrl/$key\">$key<\/a> . . . . . .  $&<br>\n";
}
}
$m = $m || No;
print "<hr>$m pages found out of $n pages searched.</body>";
}
# --------------------------------------------------------  HandleSearch

sub CookSpaces {
$CookedInput{text} =~ s/ {3,8}/\t/g
if $CookedInput{convert};
}
# --------------------------------------------------------  CookSpaces

sub HandleDiff {
$title = $CookedInput{diff};
$howfar = $CookedInput{howfar};
$howfar = 1 if ($howfar == "");
%old = &RetrievePage($title);
my $prevrev = $old{rev}-$howfar;
my $difftitle = "WikiDiff$title$prevrev";
`$RcsBin/rcsdiff -r$prevrev $DataBase/$title.wiki 2>&1 > $DataBase/$difftitle.wiki\n`;
$CookedInput{browse} = $difftitle;
print "<pre>\n";
print "Diffs with Revision $prevrev\n";
&HandleBrowse(1);
print "</pre>\n";
unlink "$DataBase/${difftitle}.wiki";
}
# --------------------------------------------------------  HandleDiff

sub HandleRevision {
$title = $CookedInput{revision};
$howfar = $CookedInput{howfar};
$howfar = 1 if ($howfar == "");
%old = &RetrievePage($title);
my $prevrev = $old{rev}-$howfar;
my $revisiontitle = "WikiRevision$title$prevrev";
`$RcsBin/co -p$prevrev $DataBase/$title.wiki 2>&1 > $DataBase/$revisiontitle.wiki\n`;
$CookedInput{browse} = $revisiontitle;
print <<EOF ;
Revision: $prevrev ($howfar back from <a href="$ScriptUrl/$title">current</a>)
<form method="get" action="$ScriptUrl">
<input type="hidden" name="revision" value="$title" />
<input type="text" name="howfar" value="$howfar">
<input type="submit" value="Go Back" />
</form>
<pre>
EOF
&HandleBrowse(1);
print "</pre>\n";
$revisiontitle =~ /^$LinkPattern$/ || &AbortScript("edit: improper name: $revisiontitle");
%old = &RetrievePage($revisiontitle);
$_ = $old{text};
s/\r\n/\n/g;
&EscapeMetaCharacters;
$convert = "checked" if $ENV{HTTP_USER_AGENT} =~ /WebExplorer/;
print <<EOF ;
<hr />
<pre>
<textarea name="text" rows='25' cols='75' wrap='virtual'>$_</textarea><br />
</pre>
EOF
unlink "$DataBase/${revisiontitle}.wiki";
}
# --------------------------------------------------------  HandleRevision

sub HandleLog {
$title = $CookedInput{log};
print "<pre>";
`$RcsBin/rlog $DataBase/$title.wiki\n`;
print "</pre>";
}
# --------------------------------------------------------  HandleRevision

sub LockPage {
local($title) = pop(@_);
local ($n) = 0;
$lock = "$DataBase/$title.lock";
while (mkdir($lock, 0555) == 0) {
$! == 17 || &AbortScript("can't make $lock: $!\n");  # EEXIST == 17 is OK, try later.
$n++ < 30 || &AbortScript("timed out waiting for $lock\n");
sleep(1);
}
}
# --------------------------------------------------------  LockPage

($sec, $min, $hour, $mday, $mon, $year) = localtime($^T);
$DateToday = (January, February, March, April, May, June, July,
August, September, October, November, December)[$mon]
. " " . $mday . ", " . ($year+1900);
# --------------------------------------------------------  DateToday

sub WritePage {
local($title, $value) = @_;
$file = "$DataBase/$title.wiki";
open (WDB, ">$file");
print WDB $value;
close WDB;
my $uid = &GetUserId();
print `$RcsBin/ci "-mUpdate from $page{host} user $uid" -l$page{rev}.0 $file 2>&1`;
}
# --------------------------------------------------------  WritePage

sub ReplacePage {
local($title, *page) = @_;
local($value, @value);
$page{date} = $DateToday;
$page{host} = &GetRemoteHost;
$page{agent} = $ENV{HTTP_USER_AGENT};
$page{rev}++;
@value = %page;
$value = join($FieldSeparator, @value);
&WritePage($title,$value);
}
# --------------------------------------------------------  ReplacePage

sub UnlockPage {
local($title) = pop(@_);
$lock = "$DataBase/$title.lock";
rmdir($lock);
}
# --------------------------------------------------------  UnlockPage

#$SignatureUrl = "http://www.iam.unibe.ch/~schneidr/Pics/line-funny.gif";
$SignatureUrl = "http://www.iam.unibe.ch/~schneidr/Pics/line-funny.gif";
# --------------------------------------------------------  SignatureUrl

sub ChangeNotification {
my ($pageTitle,$host) = @_;
system("mail <<EOF $AdminEmail From: Wiki\n"
        . "Subject: Wiki changed\n"
        . "Wiki '$DataBase':\n"
        . "The page $pageTitle was changed on $DateToday by $host\n"
        . "EOF\n");
}
# -------------------------------------------------------- ChangeNotification

sub HandlePost {
    $title = $CookedInput{post};
    $anchor = &AsAnchor($title);
    #$CookedInput{currency} =~ s/^[ \t]+//;
    $CookedInput{currency} =~ s/[ \t]$//;
#    if ($CookedInput{currency} && $CookedInput{currency} !~ m/No good reason/ &&
#	$CookedInput{currency} ne "" && ! $CookedInput{sessionID}) 
    if(1){
	&CookSpaces;
	&LockPage($title);
	%old = &RetrievePage($title);
	for (keys(%CookedInput)) {
	    next if /post/ || /form/ || /title/;
	    $old{$_} = $CookedInput{$_} if $CookedInput{$_};
	}
# Could include diagnostics in output ...
	$RcsMsg = &ReplacePage($title, *old);
	%rc = &RetrievePage(RecentChanges);
	$rc{text} =~ s/\t\* $title .*\n//;
	$rc{text} .= "\n$DateToday\n" unless $rc{text} =~ /$DateToday/;
	my $uid = &GetUserId();
	$rc{text} .= "\t* $title . . . . . . " . &GetRemoteHost() . " " . 
	    " [User:" . $uid . "]\n";
	&ReplacePage(RecentChanges, *rc);
	&UnlockPage($title);
	if($ThanksMsg) {
	    print <<EOF ;
	    <head><title>Thanks for $title Edits</title></head>
		<body bgcolor="white" background='$Background'>
		<p>Thank you very much for editing $anchor.</p>
		<p>Your careful attention to detail is much appreciated.</p>
		<p>Click on the link above to return to the page.</p>
		<hr>
		</body>
EOF
	    } else {
		$CookedInput{browse} = $CookedInput{post};
		&HandleBrowse;
	    }
	ChangeNotification($title,&GetRemoteHost()) if $AdminEmail;
    } else {
	print <<EO2F ;
	<head><title>OK, no problem</title></head>
	    <body bgcolor="white" background='$Background'>
	    <p>You did not explain your changes so I guess you do not want to edit $anchor.</p>
	    <p>Click on the link above to return to the page.</p>
	    <hr>
	    </body>
EO2F
	}
}
# --------------------------------------------------------  HandlePost

sub DumpBinding {
local(*dict) = @_;
print "<hr><dl>\n";
for (keys(%dict)){print "<dt>$_<dd>$dict{$_}\n";}
print "</dl><hr>\n";
}
# --------------------------------------------------------  DumpBinding

$RcsDir = "$DataBase/RCS";
# --------------------------------------------------------  RcsDir

sub BootStrap {
if (-d $DataBase) { return; }
(mkdir $DataBase, 0755) || &AbortScript("Can't mkdir $DataBase: $!");
if (!-d $RcsDir)
{ (mkdir $RcsDir, 0755) || &AbortScript("Can't mkdir $RcsDir: $!"); }
if (-f "$DataBase.pag") {
dbmopen(%db, $DataBase , 0666) || &AbortScript("Can't bootstrap $DataBase: $!");
while (($key, $value) = each %db)
{ &WritePage($key,$value); }
}
}
# --------------------------------------------------------  GetRemoteHost
sub GetRemoteHost {
return $ENV{REMOTE_HOST} if ($ENV{REMOTE_HOST});
my $a = gethostbyaddr(inet_aton($ENV{REMOTE_ADDR}), AF_INET);
return $a if ($a);
return $ENV{REMOTE_ADDR} if ($ENV{REMOTE_ADDR});
return "";
}

# from http://www.bewley.net/perl/cookie-test.pl
#- Retrieve Cookies From ENV --------------------------------------------------#
sub GetCookies {
    # cookies are seperated by a semicolon and a space, this will split
    # them and return a hash of cookies
    local(@rawCookies) = split (/; /,$ENV{'HTTP_COOKIE'});
    local(%cookies);

    foreach(@rawCookies){
	($key, $val) = split (/=/,$_);
	$cookies{$key} = $val;
    } 

    return %cookies; 
} 

# --------------------------------------------------------  HandleLogin
sub HandleLogin {
    my %cookies = &GetCookies;
    my $title = $CookedInput{edit} || $CookedInput{post};
    my $ok=0;

    if ($cookies{'phpbb2mysql_data'}) {
      my $str =$cookies{'phpbb2mysql_data'};
      $str =~ s/\%([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
      if ($str =~/s:6:"userid";s:[0-9]+:"([0-9]+)"/) {
          my $uid = $1;
          $ok = 1 if (($uid)+0 > 0);
      }
    }

    if ($ok != 1) {
	&LoginMessage($title);
	return "";
    }

    return 1; 
}

sub GetUserId {
    my %cookies = &GetCookies;
    my $userid=0;

    if ($cookies{'phpbb2mysql_data'}) {
      my $str =$cookies{'phpbb2mysql_data'};
      $str =~ s/\%([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
      if ($str =~/s:6:"userid";s:[0-9]+:"([0-9]+)"/) {
	  $userid = $1;
      }
    }

    return $userid;
}

# --------------------------------------------------------  BootStrap

# InitialComments
print "Content-type: text/html\n\n";

&BootStrap;
$CookedInput{browse} && &HandleBrowse;
$CookedInput{edit} && &HandleLogin && &HandleEdit;
$CookedInput{links}  && &HandleLinks;
$CookedInput{search} && &HandleSearch;
$CookedInput{diff} && &HandleDiff;
#$CookedInput{log} && &HandleLog;
$CookedInput{revision} && &HandleRevision;

if ($ENV{REQUEST_METHOD} eq POST) {
    $CookedInput{post} && &HandleLogin && &HandlePost;
}
#&DumpBinding(*CookedInput);
#&DumpBinding(*old);
#&DumpBinding(*ENV);
# --------------------------------------------------------  WikiInHyperPerl

