<?php
############################# readme ############################# 
#
# AgolAdmin
# $Id: agoladmin.php,v 1.36 2004/12/03 04:36:39 btanaka Exp $
# agolbloga@martingale-oak.com 
#
#
# AgolAdmin (ah goal ADD min), n. - An administrative interface for
# Agolbloga.
#
# Agolbloga (ah goal BLAH gah), n. - A simple, lightweight blogging
# engine written in PHP.
#
#
# Installation
# ------------
#
# 1. Install Agolbloga first.  See the Agolbloga script for
#    installation instructions.
#
# 2. You're back!  That means you installed Agolbloga, right?  Good!
# 
# 3. Put this script in the same directory as your Agolbloga
#    script.
#
# 4. Adjust the settings, if necessary in the User Config Zone.
#
# 5. View the script with your web browser.  If there were any
#    installation problems, you'll be advised.
#
############################# readme ############################# 

## User Config Zone ##############################################

# Set this to name of your Agolbloga script.  If you didn't change
# the name when you installed Agolbloga, the name is simply
# "agolbloga.php" and you can leave this setting as-is.
$agolbloga = "agolbloga.php";

# Set this to the same directory as $datadir in your Agolbloga
# installation.  If you're using a stock Agolbloga install, the
# directory is simply "./agolbloga.data" and you can leave this
# setting as-is.
$datadir = "./agolbloga.data";

# Set a password here.  It must be an MD5 hash.  "How do I make an
# MD5 hash?" you ask?  Simple.  Install this script first, log in
# with the default password "foo", use the "Encrypt a password"
# feature, and then edit this script and paste the result below.
# ("foo" is "cbd18db4cc2f85cedef654fccc4a4d8", by the way.)  
# Be sure to change the encrypted password to something other than
# foo or your blog will be tremendously non-secure.
$password = "cbd18db4cc2f85cedef654fccc4a4d8";

# Set this to the URL of your blog
$blog = "http://www.example.com/blog/agolbloga.php";

# Set these to the full path and name of your web server's access log
$accesslogpath = "/var/log/httpd";
$accesslogname = "access_log";

# What to look for in the log
$hitregex = "agolbloga.php";

# List any IP addresses to ignore in the stats (such as your own, 
# Google's crawlers, etc).
# Not used this version.
#$ignoreip = array();

## User Config Zone ##############################################



#
# log in attempt, either set the cookie or dont
#
$failure = 0;
if ( $_POST['knockknock'] ) {
    $logtry = $_POST['logtry'];
    #print "login attempt: $logtry"; #debug
    # check password
    $md5try = md5($logtry);
    if ( preg_match("/$password/", $md5try) ) {
	# for the cookie
	$chip = md5($logtry);
        # set cookie
	setcookie ("AgoladminLogin", "$chip", time()+3600, "/");
	startpage("AgolAdmin", "Administrative Tools for Agolbloga", $datadir);
	print "<div id=\"main\">";
	print <<<EOF
	<div class="posttitle">Success</div>
	<div class="postbody">You are now logged in!
	<p /><a href="agoladmin.php">Continue...</a></div>
	</div>
EOF;
	endpage($blog);
	exit;
    } else {
        $failure = 1;
    }
}


#
# logout
#
if ( $_GET['logout'] ) {
    setcookie ("AgoladminLogin", "", time() - 3600, "/");
    startpage("AgolAdmin", "Administrative Tools for Agolbloga", $datadir);
    print "<div id=\"main\">";
    print <<<EOF
    <div class="posttitle">Success</div>
    <div class="postbody">You are now logged out!
    <p /><a href="agoladmin.php">Continue...</a></div>
    </div>
EOF;
    endpage($blog);
    exit;
}


#
# begin main
#
startpage("AgolAdmin", "Administrative Tools for Agolbloga", $datadir);
print "<div id=\"main\">";


#
# make sure the script is installed where agolbloga is
#
if ( ! file_exists("./$agolbloga") ) {
    print "<div class=\"error\">";
    print <<<EOF
Error:<p />
No Agolbloga installation detected! 
<p />
There are two ways to resolve this problem:
<ol>
<p />
<li>
If you haven't installed Agolbloga, please do so now and then install Agoladmin.
You must install Agoladmin in the same directory as you installed Agolbloga.
<p />
<li>
If, on the other hand, you <strong>have</strong>
already installed Agolbloga and it
<strong>is</strong>
in the same directory as Agoladmin, you're probably seeing this
error because you're not using the default script name for
Agolbloga.
That's perfectly fine, but you will need to change the
&#36;agolbloga setting in the Agoladmin script.  Fix that, and this
error will vanish.
</ol>
EOF;
    print "</div>";
    print "</div>";
    endpage($blog);
    exit;
}


#
# make sure they've set the blog variable.  
#
if ( preg_match("/example.com/", $blog) ) {
    print <<<EOF
<div class="error">
Error:<p />
You haven't set the 
&#36;blog setting in the Agoladmin script.  
Set &#36;blog to the URL of your blog.
</div>
</div>
EOF;
    endpage($blog);
    exit;
}


#
# cookietest
#
cookietest($_COOKIE, $failure, $blog);


## prerequisite directories test ################################# 
#
# see if the data directory exists. if it doesn't then warn.
#
isdatadir($datadir);
#
# see if the archive directory is writeable.
# if it doesn't then create it.
#
$archivedir = "$datadir" . "/archive";
isarchivedir($archivedir);
#
## prerequisite directories test ################################# 


#
# try to detect non timestamp filenames
# if you find any, warn
#
$dirarray = array("$datadir", "$datadir/archive");
foreach ( $dirarray as $curdir ) {
$dir = "$curdir";
$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
    #if ( preg_match("/\d{10,}/", $filename) ) {
    if ( preg_match("/.*.txt/", $filename) ) {
	if ( ! preg_match("/\d{10,}/", $filename) ) {
	    print "<div class=\"postbody\">";
	    print "<div class=\"error\">";
	    print "Error:<p />";
	    $modtime = filemtime("$dir/$filename");
	    print <<<EOF
The filename $dir/$filename conforms to Agolbloga
requirements, but does not match the filename format required for Agoladmin.
(Agoladmin requires that filenames be the Unix timestamp that
corresponds to the last modtime of the file when the file is created.)
Please rename it to $modtime.txt. 
EOF;
	    print "</div>";
	    print "</div>";
	    print "</div>";
	    endpage($blog);
	    exit;
	}
    }
}
closedir($dh);
}


#
# try to detect non writable files.  
#
$dirarray = array("$datadir", "$datadir/archive");
foreach ( $dirarray as $curdir ) {
$dir = "$curdir";
$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
    #if ( preg_match("/\d{10,}/", $filename) ) {
    if ( preg_match("/.*.txt/", $filename) ) {
	if ( ! is_writable("$dir/$filename") ) {
	    print "<div class=\"postbody\">";
	    print "<div class=\"error\">";
	    print "Error:<p />";
	    print <<<EOF
The filename $dir/$filename is not writable by the web server.  In
order for Agoladmin to work properly, all .txt files must be writeable
by the web server.  Please make sure that your .txt files are owned
by the web server process owner (usually nobody or www) and try
again. Exiting...
EOF;
	    print "</div>";
	    print "</div>";
	    print "</div>";
	    endpage($blog);
	    exit;
	}
    }
}
closedir($dh);
}


#
# Menu
#
if ( preg_match("/$password/", $_COOKIE[AgoladminLogin]) ) {
    menu($blog, $_COOKIE);
} else {
    welcome($blog);
}


#
# edit externals
#
if ( $_GET['a'] == 300 ) {
$external = $_GET['external'];
badtest($external);
print "<div class=\"posttitle\">";
print "Editing $external";
print "</div>";
    print "<div class=\"postbody\">";
# read file into a form
if ( ! file_exists("$datadir/$external") ) {
    print "You do not have the <strong>optional</strong>";
    print " external file $datadir/$external ";
    print "installed.  See the Agolbloga help page for information ";
    print "</div>";
} else {
       if ( ! $file = fopen ("$datadir/$external", "r") ) {
	    print "error: could not open blurb!\n";
	    exit;
	} else {
	    while (!feof($file)) {
		$string = fgets($file, 4096);
		$bigstring .= "$string";
		}
	    } 
	    print <<<EOF
<form method="post" action="agoladmin.php">
<textarea name="stuff" cols="80" rows="20">
$bigstring
</textarea><p />
Warning!  Be sure you understand thoroughly what will happen if you
change this file.  There is no un-do.  There is no preview.  Before
you alter any of the external files, read the Agolbloga help page
section relating to the file you would like to change.
<p />
<input type="hidden" name="a" value="301">
<input type="hidden" name="external" value="$external">
<input type="submit" name="submit" value="Save">
</form>
</div>
EOF;
	}
}


#
# edit externals, commit
#
if ( $_POST['a'] == 301 ) {
$external = $_POST['external'];
badtest("$external");
$stuff = $_POST['stuff'];
$stuff = stripslashes("$stuff");
$filename = $datadir . "/" . $external;
print "<div class=\"posttitle\">";
print "Saving $external";
print "</div>";
print "<div class=\"postbody\">";
if ( ! $file = fopen("$filename", 'w')) {
    print "Cannot open file ($filename)";
    exit;
}
if (fwrite($file, $stuff) === FALSE) {
    print "Cannot write to file ($filename)";
    exit;
} else {
    print "Done!";
}
fclose($file);
print "</div>";
}


#
# help
#
if ( $_GET['a'] == 160 ) {
print <<<EOF
<div class="posttitle">Help</div>
<div class="postbody">
<ul>
<li><a href="$blog?help=1">Agolbloga Help</a>
<li><a href="#login">Login / Logout</a>
<li><a href="#newpost">New Post</a>
<li><a href="#home">Home</a>
<li><a href="#view">View Blog</a>
<li><a href="#editcurrent">Edit, Delete, or Prune (current)</a>
<li><a href="#editarchive">Edit or Delete (archive)</a>
<li><a href="#encrypt">Encrypt Password</a>
<li><a href="#conflict">Resolve Conflicts</a>
<li><a href="#filenames">Filenames</a>
<li><a href="#install">Installation</a>
</ul>

<a name="login"></a>
<div class="posttitle">Login / Logout</div>
Agoladmin has a very simple authentication scheme.  It requires
only that
the Agoladmin script be configured properly and that cookies are
turned on in your browser.  See the script itself for configuration
information.  Once the script is properly configured, you may
log in at any time using the login dialog box at the top of the
page.  To log out, simply select the "logout" link at the top of
the page.
<div class="postbody">
</div>

<a name="newpost"></a>
<div class="posttitle">New Post</div>
<div class="postbody">
This is the tool you will probably use most often.  Select New Post
to compose and publish new blog posts.
</div>

<a name="home"></a>
<div class="posttitle">Home</div>
<div class="postbody">
Selecting this link in the menu will return you to the main
Agoladmin page.
</div>

<a name="view"></a>
<div class="posttitle">View Blog</div>
<div class="postbody">
Selecting this link in the menu will 
take you to your blog so you can view any changes you have made.
</div>

<a name="editcurrent"></a>
<div class="posttitle">Edit, Delete, or Prune (current)</div>
<div class="postbody">
You can edit, delete, or prune any of the posts on the main
(current) page of your blog.  Edit allows you to change the text of
an entry.  Delete allows you to remove an entry from your blog.
Prune removes an entry from the main page, but leaves the archived,
permalinked version intact.  This is an excellent way of managing
the number of posts on your main page.
<p />
Other blogging engines allow you to set a fixed number of entries
(or a date range) to leave un-pruned on your main page.  While this
is a perfectly logical approach, I've often found that I wanted to
determine myself how many posts were displayed on the main page
based on content, not number or age.  With this in mind, I'm using
manual pruning.  It's possible that in the future there will be
auto-pruning as well if demand arises.
</div>

<a name="editarchive"></a>
<div class="posttitle">Edit or Delete (archive)</div>
<div class="postbody">
This feature is exactly like "Edit, Delete, or Prune (current)", but
operates solely on posts that are only in the archive.  Prune is not
included since it is irrelevant in this context.
</div>

<a name="encrypt"></a>
<div class="posttitle">Encrypt Password</div>
<div class="postbody">
Agoladmin requires that passwords be stored in an "encrypted" format.
Use this utility to convert plain passwords to their encrypted
equivelants.
</div>

<a name="conflict"></a>
<div class="posttitle">Resolve Conflict</div>
<div class="postbody">
Conflicts should be very rare in Agolbloga, but if they do arise,
they may cause minor complications.  To learn more about conflicts
and how to resolve them with the provided tools, please read the
instructions in the Resolve Conflict tool itself.
</div>

<a name="filenames"></a>
<div class="posttitle">Filenames</div>
<div class="postbody">
While Agolbloga requires only that filenames end in .txt, 
Agoladmin requires that filenames be the Unix timestamp of the last
modtime of the file when the file is first created.
</div>

<a name="install"></a>
<div class="posttitle">Installation</div>
<div class="postbody">
If you've installed Agoladmin and you've made it far enough to see
this help section, but you're still having configuration problems,
here's a quick checklist of things you should do:
<ol>
<li>
Be sure you've installed Agolbloga properly and in the same
directory as Agoladmin first.
<li>
Adjust the settings in the "User Config Zone" section according to
the instructions in the comments for each setting.
<li>
If you're still having trouble, visit the Agolbloga website.  You
can reach the Agolbloga website via the "About" page, which you can
reach via the "Powered by..." link at the bottom of this page.
</ol>
</div>

</div>
EOF;
}


#
# New Post
#
if ( $_POST['newpost'] ) {
    $editname = $_POST['editname'];
    $newtitle = $_POST['newtitle'];
    $newbody = $_POST['newbody'];
    $newtitle = stripslashes($newtitle);
    $newbody = stripslashes($newbody);
    newpost($newtitle, $newbody, $editname);
    print "</div>";
    endpage($blog);
    exit;
}


#
# Publish Post (after preview)
#
if ( $_POST['publishpost'] ) {
    $newtitle = $_POST['newtitle'];
    $newbody = $_POST['newbody'];
    $editname = $_POST['editname'];
    $try = $_POST['password'];
    $newtitle = stripslashes($newtitle);
    $newbody = stripslashes($newbody);
    publishpost($newtitle, $newbody, $datadir, $password, $try, $blog, $editname);
    print "</div>";
    endpage($blog);
    exit;
}


#
# Not Yet
#
if ( $_GET['a'] == 200 ) {
print <<<EOF
<div class="posttitle">Not Yet!</div>
<div class="postbody">
Unfortunately, this feature does not yet exist.
</div>
EOF;
}


#
# New Post
#
if ( $_GET['a'] == 100 ) {
print <<<EOF
<div class="posttitle">New Post</div>
<div class="postbody">
EOF;
if (! is_writable("$datadir") ) {
print <<<EOF
    <div class="error">Error: 
    The directory $datadir is not writable by the webserver.  Check
    permissions and/or ownership on $datadir.  Consider also that
    you may not have set the datadir variable correctly.  It must
    point to the same directory as the datadir variable in your
    Agolbloga installation.  If you have not finished your Agolbloga
    installation yet, please stop configuring Agoladmin, finish
    installing Agolbloga, and then come back to this script.
    <p />
    Note that if you're using a stock Agolbloga install, this
    behavior is normal.  The datadir is ordinarily NOT writable by
    the webserver for added security.  However, if you want to use
    Agoladmin to manage your blog, you must make datadir writable by
    the webserver.  While is this is slightly less secure, it is not
    radically less secure and should be fine, provided you observe
    normal security precautions on your server.
    </div>
    </div>
EOF;
} else {
print <<<EOF
    <form action="agoladmin.php" method="post">
    <p />
    Use the form below for your new post.  Don't forget to separate
    paragraphs with &lt;p />.
    <p />
    Title:<br />
    <input type="text" name="newtitle" size="60">
    <p />
    Body:<br />
    <textarea name="newbody" rows="10" cols="60">
    </textarea>
    <p />
    <input type="hidden" name="newpost" value="1">
    <input class="buttfont" type="submit" name="submit" value="Preview"><p />
    <input class="buttfont" type="reset">
    </form>
    </div>
EOF;
}
} # end of new post form


#
# Encrypt Password
#
if ( ( $_GET['a'] == 110 ) || ( $_POST['a'] == 110 ) ) {
print <<<EOF
<div class="posttitle">Encrypt Password</div>
<div class="postbody">
<form action="agoladmin.php" method="post">
<input type="text" name="cleartext">
<input type="hidden" name="encrypt" value="1">
<input type="hidden" name="a" value="110">
<input type="submit">
</form>
EOF;
if ( $_POST['encrypt'] ) {
    $ciphertext = md5($_POST['cleartext']);
    print "$_POST[cleartext] = $ciphertext";
}
print "</div>";
}


#
# Edit Post, Make Menu
#
if ( $_GET['a'] == 120 ) {
print <<<EOF
<div class="posttitle">Edit, Delete, or Prune Post (current or
archive)</div>
<p />
Below you will find a list of your posts.  Below each post,
you will find three links: "Edit", "Delete", and "Prune".
<p />
<ul>
<li>"Edit"  - Allows you to edit the post.
<p /><li>"Delete"  - Removes the post from both the current main page and
the archive.  In other words, the post is completely removed from
your blog.
<p /><li>"Prune" - Removes the post from the current main page
only.  The archived version will remain intact, and will be
accessible via search, archive listing, and, most importantly,
permalink.  Remember, the permalink for each post always points to the archive,
never to the main page.
</ul>
EOF;
print "<p />";
$iscur = $_GET['iscur'];
if ( $iscur == 2 ) {
    # if iscur 2 (archive only), then get curs anyway so we can drop
    # them from the other array later.  we dont want to list current items in
    # an archive only listing.
    $dir = "$datadir";
    $dh  = opendir($dir);
    if ( $iscur == 2 ) {
	$mainfiles = array();
	while (false !== ($filename = readdir($dh))) {
	    if ( preg_match("/.txt$/", $filename) ) {
		$mainfiles[] = $filename;
	    }
	}
	#print_r($mainfiles); #debug
    }
    closedir($dh);
    # set datadir to datadir and archive for the rest
    $datadir .= "/archive";
}
if ( $iscur == 2 ) {
    print "<div class=\"posttitle\">Posts in archive ($datadir)</div>"; 
    print "<div class=\"postbody\">";
} else {
    print "<div class=\"posttitle\">Current posts in main ($datadir)</div>"; 
    print "<div class=\"postbody\">";
}
$dir = "$datadir";
$dh  = opendir($dir);
$padcount = 0;
$files = array();
while (false !== ($filename = readdir($dh))) {
    # if iscur 2 dont add to array if also in mainfiles
    if ( ( $iscur == 2 ) && ( in_array( "$filename", $mainfiles) )) {
	continue;
    }
    $modtime = filemtime("$datadir/$filename");
    $combo = "$modtime" . ":" . "$filename";
    if ( preg_match("/.txt$/", $combo) ) {
        $padcount++;
        $files[] = $combo;
    }
}
closedir($dh);
# sort them, reverse chronologically (standard blog order)
rsort($files);
#print_r($files);
# open each file, and print the title as a link
#$foreachcount = 0;
foreach ( $files as $i) {
#    $foreachcount++;
#    if ( $foreachcount > 10 ) {
#        break;
#    }
    list($date, $name) = split(":", $i);
    if ( ! $file = fopen ("$datadir/$name", "r") ) {
        print "error: could not open blurb!\n";
        exit;
    } else {
        $count = 0;
        while (!feof($file)) {
            $count++;
            $string = fgets($file, 4096);
            if ( $count == 1 ) {
		print "<div class=\"posttitle2\">";
		print "$string</div>";
		print "<a href=\"./agoladmin.php?editname=$datadir/$name\">Edit</a>";
		if ( $iscur != 2 ) {
		    print " ~ <a href=\"./agoladmin.php?delname=$name&nukelevel=1\">Delete</a>";
		    print " ~ <a href=\"./agoladmin.php?delname=$name&nukelevel=2\">Prune</a>";
		} else {
		    print " ~ <a href=\"./agoladmin.php?delname=$name&nukelevel=3\">Delete</a>";
		}
	    print "<p />";
            }
        }
        #$pdate = date("l F j, Y - g:i a ", $date);
    }
}
print "</div>";
print "</div>";
#endpage($blog);
}


#
# Edit Post, Specific Post
#
$editname = $_GET['editname'];
if ( preg_match("/\d+\.txt/", $editname) ) {
    badtest("$editname");
    if ( ! $file = @fopen ("$editname", "r") ) {
	print "<div class=\"error\">";
	print "Error: Post $name is unreadable!\n";
	print " Check ownership and permissions!\n";
	print "</div>\n";
	#exit;
    } else {
	$count = 0;
	$oldbody = "";
	while (!feof($file)) {
	    $count++;
	    $string = fgets($file, 4096);
	    $trimmed = rtrim($string);
	    if ( $count ==1 ) {
		$oldtitle = "$trimmed";
	    } else {
		$oldbody .= "$string";
	    }
	}
    }
    ltrim($oldbody);
    print <<<EOF
<div class="posttitle">Edit Post</div>
<p />
Editing post: "$editname"
<form action="agoladmin.php" method="POST">
<p />
Don't forget to separate paragraphs with &lt;p />.
<p />
Title:<br />
<input type="text" name="newtitle" size="60" value="$oldtitle">
<p />
Body:<br />
<textarea name="newbody" rows="10" cols="60">
$oldbody
</textarea>
<p />
<input type="hidden" name="newpost" value="1">
<input type="hidden" name="editname" value="$editname">
<input class="buttfont" type="submit" name="submit" value="Preview"><p />
<input class="buttfont" type="reset">
</form>
</div>
EOF;
    print "</div>";
    endpage($blog);
}


#
# Delete Post, Current 
#
# this section is beggging for refactoring
#
if ( isset($_GET['delname']) ) {
    $delname = $_GET['delname'];
} else {
    $delname = $_POST['delname'];
}
badtest("$delname");
# nukelevel - 1 both 2 current 3 archive
if ( isset($_GET['nukelevel']) ) {
    $nukelevel = $_GET['nukelevel'];
} else {
    $nukelevel = $_POST['nukelevel'];
}
$nuketime = $_POST['nuketime'];
$try = $_POST['try'];
if ( preg_match("/\d+\.txt/", $delname) ) {
    if ( $nuketime != 1 ) { # not time to nuke, see else
        if ( $nukelevel == 3 ) {
	    $datadir .= "/archive";
	}
	if ( ! $file = @fopen ("$datadir/$delname", "r") ) {
	    print "<div class=\"error\">";
	    print "Error: Post $name is unreadable!\n";
	    print " Check ownership and permissions!\n";
	    print "</div>\n";
	    #exit;
	} else {
	    $count = 0;
	    $oldbody = "";
	    while (!feof($file)) {
		$count++;
		$string = fgets($file, 4096);
		$trimmed = rtrim($string);
		if ( $count ==1 ) {
		    $oldtitle = "$trimmed";
		} else {
		    $oldbody .= "$string";
		}
	    }
	}
	ltrim($oldbody);
	print <<<EOF
<div class="posttitle">Delete or Prune Post</div>
<p />
EOF;
	print "Delete post $delname";
	if ( $nukelevel == 1 ) {
	    print " from main (\"current\") page and archive?";
	    print " If you want to delete the post from the main page,";
	    print " but leave the archive alone, use 'prune' instead.";
	} elseif ($nukelevel == 2) {
	    print " from main (\"current\") page only? (Prune)";
	} elseif ($nukelevel == 3) {
	    print " from archive only?";
	}
	print <<<EOF
<form action="agoladmin.php" method="POST">
<!-- Password: <input type="password" name="try"><br /> -->
<input type="hidden" name="nukelevel" value="$nukelevel">
<input type="hidden" name="nuketime" value="1">
<input type="hidden" name="delname" value="$delname">
<input class="buttfont" type="submit" name="submit" value="Delete">
<p /> <div class="posttitle">$oldtitle</div>
<p /> <div class="postbody">$oldbody</div>
</form>
</div>
EOF;
	print "</div>";
	#endpage($blog);
    } else { # time to nuke
	# check password
	#$md5try = md5($try);
	if ( ! preg_match("/$password/", $_COOKIE[AgoladminLogin]) ) {
	    #print "$password<br /> $md5try"; #debug
	    print "You are not authorized to alter this blog,";
	    print " or you entered your password incorrectly.";
	    print "</form>";
	    print "<form>";
	    print "<input type=button value=\"Back\" onCLick=\"history.back()\">";
	    print "</form>";
	    exit;
	}
	#print "$nukelevel";
	if ( ( $nukelevel == 1 ) || ( $nukelevel == 2 ) ) { 
	    print "Deleting $datadir/$delname...<br />";
	    if (! @unlink("$datadir/$delname") ) {
	        print "Cannot unlink $datadir/$delname!";
	    }
	}
	#if ( $nukelevel == 1 ) { 
	if ( ( $nukelevel == 1 ) || ( $nukelevel == 3 ) ) { 
	    print "Deleting $datadir/archive/$delname...<br />";
	    print "Deleting $datadir/archive/$delname.comments...<br />";
	    if (! @unlink("$datadir/archive/$delname") ) {
	        print "Cannot unlink $datadir/archive/$delname!";
	    }
	    if (! @unlink("$datadir/archive/$delname.comments") ) {
	        print "Tried to delete $datadir/archive/$delname.comments";
		print " but there were no comments.  That's ok.";
	    }
	}
    }
}


#
# Resolve Conflicts
#
if ( $_GET['a'] == 140 ) {
print <<<EOF
<div class="posttitle">Resolve Conflicts</div>
<div class="postbody">
<form action="agoladmin.php" method="POST">
Conflicts arise when a
previously archived post and a new post share the same name but
appear to be different in content.
If you are using Agoladmin to manage your blog, or if you're using
the mkpost shell script, <strong>you should never run into 
conflicts</strong>.  Conflicts should only arise if: a) you are manually
choosing filenames for your posts, or b) your server suffers a time
drift.
<p />
If Agolbloga has determined that there is a conflict, it will print
a warning at the bottom of your main page.
In the warning, the conflicting
file will be identified by name.  Paste or type that name here then 
select "OK":
<p />
<input type="text" name="conflicted">
<input type="submit" name="inspect" value="Inspect">
</form>
</div>
EOF;
}


#
# show conflicting versions
#
$inspect = $_POST['inspect'];
$conflicted = $_POST['conflicted'];
if ( preg_match("/Inspect/", $inspect) ) {
    if ( ! @file_exists ("$datadir/$conflicted") ) {
	print "error: could not open $datadir/$conflicted!\n";
	exit;
    }
    print "<form method=\"post\" action=\"agoladmin.php\">";
    $shinynewfilename = "$datadir/" . date("U") . ".txt";
    print <<<EOF
    <div class="postbody">
    <div class="posttitle">Choose one</div>
    <input type="radio" name="conflictchoice" value="keepmain">
    Keep version #1 and update the archive accordingly.
    (Essentially, this means you've manually edited the file
    in question and you want now to bring the current version and
    the archive version into synch.)
    <br />
    <input type="radio" name="conflictchoice" value="renamemain">
    Keep both versions and change filename of version #1 to:
    $shinynewfilename.  (Essentially, this means you meant
    to make an entirely new post manually, but you happened to
    choose a filename already in the archive. Choosing
    this option makes the two posts two independent entities.)
    <p />
    <input type="hidden" name="conflicted" value="$conflicted">
    <input type="hidden" name="shinynewfilename" value="$shinynewfilename">
    <input type="submit" name="resolve" value="Resolve">
    <input type="reset" name="reset" value="Reset Form">
    </div>
EOF;
    $ddarray = array("$datadir", "$datadir/archive");
    $ddcount = 0;
    foreach ( $ddarray as $dd ) {
	$ddcount++;
	print "<div class=\"posttitle\">";
	print "Version #$ddcount ($dd/$conflicted)";
	print "</div>";
	print "<div class=\"postbody\">";
	if ( ! $file = @fopen ("$dd/$conflicted", "r") ) {
	    print "error: could not open $dd/$conflicted!\n";
	    exit;
	} else {
	    $count = 0;
	    while (!feof($file)) {
		$count++;
		$string = fgets($file, 4096);
		if ( $count == 1 ) {
		    print "<div class=\"posttitle2\">$string</div>\n";
		    print "<div class=\"postbody\">";
		} else {
		    print "$string";
		}
	    }
	}
	fclose($file);
	print "</div>\n";
	print "</div>\n";
    }
    print "</form>";
}


#
# resolve conflict, final step
#
$conflicted = $_POST['conflicted'];
$shinynewfilename = $_POST['shinynewfilename'];
$conflictchoice = $_POST['conflictchoice'];
$resolve = $_POST['resolve'];
if ( preg_match("/Resolve/", $resolve) ) {
if ( ! preg_match("/$password/", $_COOKIE[AgoladminLogin]) ) {
    #print "$password<br /> $md5try"; #debug
    #print "$password, $_COOKIE[AgoladminLogin]"; #debug
    print "You are not authorized to alter this blog,";
    print " or you entered your password incorrectly.";
    print "</form>";
    print "<form>";
    print "<input type=button value=\"Back\" onCLick=\"history.back()\">";
    print "</form>";
    exit;
}
    #print "$conflictchoice"; #debug
    $touchtime = basename($conflicted, ".txt");
    if ( preg_match("/keepmain/", $conflictchoice) ) {
	if ( ! touch("$datadir/$conflicted", $touchtime) ) {
	    print "Could not re-timestamp $datadir/$conflicted";
	    exit;
	}
	print "Deleting archive of $conflicted...";
	if (! @unlink("$datadir/archive/$conflicted") ) {
	    print "Cannot unlink $datadir/archive/$conflicted!";
	} else {
	    # copy to archive, touch archive
	    if ( ! copy("$datadir/$conflicted", "$datadir/archive/$conflicted")) {
		print "Could not re-timestamp $datadir/archive/$conflicted";
		exit;
	    }  else {
		if ( ! touch("$datadir/archive/$conflicted", $touchtime) ) {
		    print "Could not re-timestamp $datadir/archive/$conflicted";
		    exit;
		}
	    } 
	}
    }
    if ( preg_match("/renamemain/", $conflictchoice) ) {
        print "Renaming $datadir/$conflicted to $shinynewfilename";
	if ( ! @rename("$datadir/$conflicted", "$shinynewfilename") ) {
	    print "<p />error: could not rename $datadir/$conflicted to ";
	    print "$shinynewfilename";
	    exit;
	}
    }
}


#
# Stats
#
if ( $_GET['a'] == 150 ) {
print "<div class=\"posttitle\">Stats</div> <div class=\"postbody\">";
if ( $_GET['stats'] ) {
    # calculate stats
    $today = date("U");
    $yesterday = ( $today - 86400 );
    $fyes = date("d/M/Y", $yesterday);
    #print "$fyes"; #debug
    badtest("$accesslogname");
    if ( ! $file = @fopen ("$accesslogpath/$accesslogname", "r") ) {
	print "<div class=\"error\">";
	print "Error: $accesslogpath/$accesslogname is unreadable!\n";
	print " Skipping stats calculation.\n";
	print "</div>\n";
	print "</div>\n";
	print "</div>\n";
	endpage($blog);
	exit;
    } else {
	$count = 0;
	$hitlines = array();
	while (!feof($file)) {
	    $string = fgets($file, 4096);
	    #print "$string"; #debug
	    if ( ( preg_match("/$hitregex/", $string) ) &&
	    ( preg_match("-$fyes-", $string) ) 
	    ) {
		#print "$string"; #debug
		$hitlines[] = $string;
		$ycount++;
	    }
	}
    }
print <<<EOF
Note: As of this version, the stats calculation is extremely
primitive.  It simply counts the number of times the agolbloga
script was served by the webserver yesterday.  In future versions,
there will be a user configurable exclusion list (to not count
your own hits, hits by crawlers, etc), stats for more than just
yesterday, etc.
<p />
$ycount hits yesterday ($fyes)
<p />
<pre>
EOF;
foreach ( $hitlines as $hitline ) {
print "$hitline";
}
print <<<EOF
</pre>
<!-- <p /> <a href="agoladmin.php?stats=0">Hide</a>. -->
EOF;
} else {
print <<<EOF
<a href="agoladmin.php?stats=1&a=150">Calculate</a>. (This may take
a while, depending on the size of your access log.)
EOF;
}
print " </div>";
}

print <<<EOF
</div>
EOF;


#
# say goodnight
#
endpage($blog);


############################## functions ##############################

# ---------------------------------------------------------------------
function startpage($title, $subtitle, $datadir) {
print <<<EOF
<html>
<head>
<title>$title</title>
<style type="text/css">
body {
    background: #dfdfdf;
    font-family: sans-serif;
    font-size: 12px;
}
a {
    color: #900;
}
.error {
    color: #f00;    
    padding: 10px 10px 5px 10px;
    margin: 0px 0px 0px 0px;
}
div#outerbox {
    padding: 0px 0px 0px 0px;
    margin: 20px 50px 0px 50px;
    border: 1px solid #000;
    background: #fff;
    /* border: 5px solid green; */  /* debug */
}
div#blogtitle {
    padding: 10px 10px 5px 10px;
    margin: 0px 0px 0px 0px;
    font-size: 18px;
    font-weight: bold;
    color: #fff;
    background: #000;
    border-bottom: 7px solid #afafaf;
}
div#blogsubtitle {
    padding: 7px 0px 0px 0px;
    margin: 0px 0px 0px 0px;
    font-size: 10px;
    font-weight: normal;
    text-align: left;
}
div.menu {
    margin: 0px 0px 30px 0px;
    padding: 12px 12px 2px 12px;
    background: #dfdfdf;
}
div.box1 {
    padding: 10px 10px 10px 10px;
    margin: 0px 0px 0px 0px;
    background: #fff;
}
div#side {
    float: right;
    width: 25%;
    padding: 10px 10px 10px 10px;
    margin: 20px 0px 0px 0px;
    border-left: 1px dashed black;
}
div#main {
    padding: 20px 18px 0px 18px; 
    margin: 0px 0px 0px 0px; 
    background: #fff;
}
div.posttitle {
    font-weight: bold;
    font-size: 12px;
    padding: 0px 0px 0px 0px;
    margin: 0px 0px 10px 0px;
    border-bottom: 1px dashed black;
    /* border: 1px dashed red; */
    /* z-index: 9; */
}
div.posttitle2 {
    font-weight: bold;
    font-size: 12px;
    padding: 0px 0px 0px 0px;
    margin: 0px 0px 0px 0px;
}
div.postbody {
    border: 0px solid black;
    line-height: 1.5em;
    margin: 0px 0px 20px 0px;
    /* border: 1px dashed red; */
}
div#byme {
    padding: 0px 0px 0px 0px;
    margin: 4px 50px 0px 50px;
    font-size: 0.85em;
    text-align: right;
}
.buttfont {
    font-family: sans-serif;
    font-size: 12px;
}
.cookietest {
    padding: 0px 12 0px 12px;
    margin: 0px 0px 2px 0px;
    font-family: serif;
    font-style: italic;
    text-align: right;
}
</style>
</head>
<body>
<div id="outerbox">
<div id="blogtitle">
    $title
    <div id="blogsubtitle">$subtitle</div>
</div>
EOF;
}


# ---------------------------------------------------------------------
function endpage($blog) {
print <<<EOF
</div> <!-- outerbox -->
<div id=byme>powered by
<a href="$blog?about=1">Agolbloga</a></div>
</body>
</html>
EOF;
}


# ---------------------------------------------------------------------
function  newpost($newtitle, $newbody, $editname) {
#print ">>> $editname"; #debug
    #print ">>>> $newbody <<< "; exit;
print <<<EOF
    <div class="posttitle">
    $newtitle
    </div>
    <div class="postbody">
    $newbody
    </div>
EOF;
$newtitle = urlencode($newtitle);
$newbody = urlencode($newbody);
print <<<EOF
    <form action="agoladmin.php" method="post">
    <input type="hidden" name="newtitle" value="$newtitle">
    <input type="hidden" name="newbody" value="$newbody">
    <input type="hidden" name="editname" value="$editname">
    <input type="hidden" name="publishpost" value="1">
    <input type="submit" name="submit" value="Publish">
    </form>
    <form>
    <input type=button value="Back" onCLick="history.back()">
    </form>
EOF;
}


# ---------------------------------------------------------------------
function  publishpost($newtitle, $newbody, $datadir, $password, $try, $blog, $editname) {
# check password
#$md5try = md5($try);
if ( ! preg_match("/$password/", $_COOKIE[AgoladminLogin]) ) {
    #print "$password<br /> $md5try"; #debug
    #print "$password, $_COOKIE[AgoladminLogin]"; #debug
    print "You are not authorized to post to this blog,";
    print " or you entered your password incorrectly.";
    print "</form>";
    print "<form>";
    print "<input type=button value=\"Back\" onCLick=\"history.back()\">";
    print "</form>";
    exit;
}
# make a new filename if no editname
#print ">>> $editname";
if ( ! preg_match("/.+/", $editname) ) {
    $filename = "$datadir/" . date("U") . ".txt";
} else {
    $filename = "$editname";
    badtest($editname);
    # get touch time string
    $touchtime = basename($editname, ".txt");
}
print "Creating file $filename...\n";
#print "directory $datadir.\n"; #debug
#print "$newtitle<br />\n"; #debug
#print "$newbody"; #debug
# urldecode
$newtitle = urldecode($newtitle);
$newbody = urldecode($newbody);
$content = "$newtitle\n\n";
$content .= "$newbody\n";
if ( ! $file = fopen("$filename", 'w')) {
    print "Cannot open file ($filename)";
    exit;
}
if (fwrite($file, $content) === FALSE) {
    print "Cannot write to file ($filename)";
    exit;
}
fclose($file);
#
# this is an edit not a new post
#
if ( $touchtime > 0 ) {
    print " Setting post timestamp back to original...";
    # if this is an archive only edit, then only need to touch archive
    # else touch and resolve conflict
    if ( preg_match("/\/archive\//", $filename) ) {
    	#print ">>> this is an archive only "; #debug
	if ( ! touch("$filename", $touchtime) ) {
	    print "Could not re-timestamp $filename";
	    exit;
	}
    } else {
    	#print ">>> this is a 'both'"; #debug
	# touch current, delete archive
	if ( ! touch("$filename", $touchtime) ) {
	    print "Could not re-timestamp $filename";
	    exit;
	} else {
	    if ( ! unlink("$datadir/archive/$touchtime.txt") ) {
		print "Could not resolve archive conflict";
		print " with $datadir/archive/$touchtime.txt";
	    }
	}
	# copy to archive, touch archive
	if ( ! copy("$filename", "$datadir/archive/$touchtime.txt") ) {
	    print "Could not re-timestamp $datadir/archive/$touchtime.txt";
	    exit;
	}  else {
	    if ( ! touch("$datadir/archive/$touchtime.txt", $touchtime) ) {
		print "Could not re-timestamp $datadir/archive/$touchtime.txt";
		exit;
	    }
	} 
    }
}
print "<p />Done!<p />\n";
}


# ---------------------------------------------------------------------
function menu($blog) {
print <<<EOF
<div class="menu">
<a href="agoladmin.php">Home</a> ~
<a href="agoladmin.php?a=160">Help</a> ~
<a href="$blog" target="_blank">View blog</a> ~
<!-- <a href="agoladmin.php?a=160">Alter Date</a> ~ -->
<a href="agoladmin.php?a=110">Encrypt Password</a> ~
<a href="agoladmin.php?a=140">Resolve Conflicts</a> ~
<a href="agoladmin.php?a=150">Stats</a> 
<p />
<a href="agoladmin.php?a=100">New Post</a> ~
<a href="agoladmin.php?a=120&iscur=1">Edit, Delete, or Prune</a> (current) ~
<a href="agoladmin.php?a=120&iscur=2">Edit or Delete</a> (archive)
<p />
"Optional Externals":
<a href="agoladmin.php?a=300&external=blacklist">Blacklist</a> ~
<a href="agoladmin.php?a=300&external=config">Config</a> ~
<a href="agoladmin.php?a=300&external=style.css">Style</a> ~
<a href="agoladmin.php?a=300&external=sidebar">Sidebar</a>
</div>
<p />
EOF;
}


# ---------------------------------------------------------------------
function welcome($blog) {
print <<<EOF
<div class="posttitle"> Welcome </div>
<div class="postbody"> Welcome to Agoladmin, the administrative
interface for Agolbloga.  Please use the login form above to begin
managing your blog.  If you're having difficulty logging in, please
consult the Agoladmin script.</div>
</div>
EOF;
endpage($blog);
}


# ---------------------------------------------------------------------
function cookietest($cookie, $failure, $blog) {
    if ( ! preg_match("/.+/", $_COOKIE[AgoladminLogin]) ) {
	print "<form action=\"agoladmin.php\" method=\"post\">";
	print "<div class=\"cookietest\">";
	if ( $failure ) {
	    print "incorrect password... ";
	}
	print "not logged in... ";
	print "<input type=\"password\" name =\"logtry\" size=\"12\">";
	print "<input type=\"submit\" name =\"submit\" value=\"login\">";
	print "<input type=\"hidden\" name =\"knockknock\" value=\"1\">";
	print "</form>";
	print "</div>";
	welcome($blog);
	exit;
    } else {
	print "<div class=\"cookietest\">";
	print "logged in as admin. ";
	print "<a href=\"agoladmin.php?logout=1\">logout</a>";
	print "</div>";
    }
}


# ---------------------------------------------------------------------
function badtest($filename) {
    if ( ( preg_match("/\.\./", $filename) ) || ( preg_match("/^\//", $filename) ) ) {
	print "Your request contains illegal characters. Exiting.";
	exit;
    }
}


# ---------------------------------------------------------------------
function isdatadir($datadir) {
if ( ! is_readable($datadir) ) {
    print "\n<div class=\"error\">\n";
    print <<<EOF
Error:<p />
The datadir you defined ($datadir) is not readable by the owner of
the webserver process or does not exist.
<p />
In order to correct this problem please be certain that you have
installed Agolbloga correctly first (ie. you've seen the "success"
message), and then set datadir in Agoladmin
to match datadir in Agolbloga.  If you're using the default datadir
in Agolbloga, you won't need to change datadir in Agoladmin; they
should match already.
EOF;
    print " \n</div>\n";
    print " \n</div>\n";
    endpage($scriptname);
    exit;
}
}

# ---------------------------------------------------------------------
function isarchivedir($archivedir) {
if ( ! is_writeable($archivedir) ) {
    print "\n<div class=\"error\">\n";
    print <<<EOF
Error:<p />
The archive directory you
defined ($archivedir) is not writeable by the owner of 
the webserver process or does not exist.
<p />
In order to correct this problem please be certain that you have 
installed Agolbloga correctly first (ie. you've seen the "success"
message), and then set archivedir in Agoladmin
to match archivedir in Agolbloga.  If you're using the default
archivedir 
in Agolbloga, you won't need to change archivedir in Agoladmin; they 
should match already.
EOF;
    print " \n</div>\n";
    print " \n</div>\n";
    endpage($scriptname);
    exit;
}
}


# end of agoladmin

