<?php
############################# readme ############################# 
#
# Agolbloga
# $Id: agolbloga.php,v 1.30 2004/11/13 19:02:57 btanaka Exp $
# agolbloga@martingale-oak.com 
#
#
# Agolbloga (ah goal BLAH gah), n. - A simple, lightweight blogging
# engine written in PHP.
#
#
# Installation
# ------------
#
# Quick Version:
#
# 1. Put this script on your web server and view it with your browser.
#    Follow the resulting instructions.
#
# 2. Read the Help page.  (See "Getting Help" below.)
#
# 3. For a friendlier interface see the Agoladmin section of the
#    Agolbloga website.  (See "Getting Help" below.)
#
#
# Slightly Less Quick Version:
#
# 1. You need to have (or have access to) a webserver with PHP4.
#
# 2. Install this file wherever you like.
#
# 3. Edit the User Config Zones (Pt. I and Pt. II) below to taste.
#
# 4. Create the directory you chose (or the default) for $datadir
#    and make certain that the process owner of the webserver
#    can read that directory.
#
# 5. Create $datadir/archive, and make certain that the process
#    owner of the webserver can read from and write to that directory.
#    The easiest way to adjust the privileges on the archive directory
#    in a Unix or Unix-like environment is to cd to the archive
#    directory and 'chmod 755 .', and then 'sudo chown nobody .'
#    Note: under OS X, you will probably need to use 'www' instead of
#    'nobody'.
#
# 6. Add junk to the sidebar in the sidebar area if you want to.
#
# 7. Read the 'readme' section--the one you're reading right now--in
#    its entirety.  It's reasonably short, and it tells you what you
#    need to know to get started.
#
# 8. Read the Help page.  (See "Getting Help" below.)
#
# 9. Blog on.
#
# 10. For a friendlier interface see the Agoladmin section of the
#    Agolbloga website.  (See "Getting Help" below.)
#
# For installation help, visit the Agolbloga website
# (http://www.briantanaka.com/agolbloga) or, if you're really really
# stuck, send email to: agolbloga@martingale-oak.com.  Please allow
# time for a reply.  Realistically, it could be several days.
#
#
# Getting Help
# ------------
# You can reach the Help section by following the "powered by Agolbloga"
# link to the "about" page, and then following the link on the
# "about" page to the Agolbloga help page.  Lots of info there;
# worth the read!
#
#
# Adding and Deleting Posts
# -------------------------
# [This information has been moved to the Agolbloga help page, which
# you can reach by following the "powered by Agolbloga" link to the
# "about" page, and then following the link on the "about" page to
# the Agolbloga help page.]
#
#
# Philosophy
# ----------
# - One php file runs everything.
# - Written for a nerdly, not newbie, user base.
# - Number of postfiles in datadir are the number of posts
#   on the main page.
# - Every time it's called, Agolbloga makes sure that copies of all
#   posts in datadir are archived in the archive directory.  (For 
#   permalinking.)
# - Main page shows permalink of copy living in archive for each post.
# - RSS feed is triggered by appending "?f=rss" to the URL.
#
# 
# Style (CSS)
# -----------
# [This information has been moved to the Agolbloga help page, which
# you can reach by following the "powered by Agolbloga" link to the
# "about" page, and then following the link on the "about" page to
# the Agolbloga help page.]
#
# Upgrading
# ---------
# [This information has been moved to the Agolbloga help page, which
# you can reach by following the "powered by Agolbloga" link to the
# "about" page, and then following the link on the "about" page to
# the Agolbloga help page.]
#
#
################################################################## 



## User Config Zone, Pt. I ####################################### 
#
# Note that if you'd like to use an external config, place it
# in datadir/config.  See the Help pages for more info and an
# example of an external config.
#
# If you're not using an external config, then set the datadir
# variable below, skip over the external config code block, and
# adjust the variables to taste until you reach the end of "User
# Config Zone, Pt I.

# Specify where you will store your posts.  This directory
# must be in the document root because a subdirectory of it
# will contain the permalinked archive copies of posts.
$datadir = "./agolbloga.data";

# support external config
# if the file doesn't exist, then useextside = 0
# if the file exists and is readable, then useextside = 1
# if the file exists and is not readable, then useextside = 2
$useextconfig = 0;
if ( @file_exists("$datadir/config") ) {
    $useextconfig = 1;
    if ( @is_readable("$datadir/config") ) {
        $useextconfig = 2;
    }
} else {
    $useextconfig = 0;
}
# print "$useextconfig"; #debug
if ( $useextconfig == 2 ) {
    require("$datadir/config");
    #config($scriptname);
} else {
if ( $useextconfig == 1 ) {
    print "Error: You have an external config, but it's unreadable.";
    print " Check permissions and see the help page for more information.<p />";
}

# Set the title and subtitle of your blog
$title = "Example Blog";
$subtitle = "The Agolbloga example blog...";

# What's the base url of this Agolbloga installation?
$baseurl = "http://127.0.0.1/example/agolbloga";

# Number of entries to list in default archive browse list
$maxarch = 100;

# Number of recently commented posts to show in recent comments
$maxrc = 12;

# If you want to receive an email every time someone comments,
# then set commail to 1.  Otherwise, set it to zero.
# I recommend setting this to 1 so that you can catch comment
# spammers more quickly.
# If you set it to 1, you must also set your email address in
# ownermail.
$commail = 1;

# Your email address
$ownermail = "blogperson@example.com";

# Set this to the number of pixels with which to pad short pages.
$padpad = 200;

# If you have installed any Agolbloga helpers, specify the directory
# where they are installed here.
#$helperdir = "./agolbloga.helpers";

}

## End User Config Zone, Pt. I ################################### 


#
# set scriptname
#
$scriptname = basename ( $_SERVER['PHP_SELF'] ) ;


## rss ########################################################### 
#
# if this is an rss request, then print rss and exit
#
$f = $_GET['f'];
if ( preg_match("/rss/", $f) ) {
	rss($scriptname, $permafile, $datadir, $baseurl, $maxarch, $title, $subtitle);
	exit;
}
## End rss ####################################################### 



## html headers and css style #################################### 
#
# print html headers and style
#
startpage($title, $subtitle, $datadir);
## End rss ####################################################### 



## 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 ################################# 



## User Config Zone, Pt. II ###################################### 
# sidebar
#
# You can set all your sidebar junk like links and whatnot here.
# Note that if you'd like to use an external sidebar, place it
# in datadir/sidebar.  See the Help pages for more info and an
# example of an external sidebar.
#
# Example:
#   <div id="side">
#   <strong>Menu</strong><p /> 
#   <a href="$scriptname">Home</a><br />
#   <a href="$scriptname?sa=1">Archives</a><br />
#   <a href="$scriptname?rc=1">Recent Comments</a><br />
#   <a href="$scriptname?f=rss">Syndicate (RSS 2.0)</a><p />
#   <form action="$scriptname" method="POST">
#   Search:<br />
#   <input type="text" class="fieldfont" name="searchstring" size="12">
#   <input class="buttfont" type="submit" name="ssubmit" value="ok">
#   </form>
#   <p /> 
#   <strong>Links</strong><p />
#   <a href="">Example Link 1</a><br />
#   <a href="">Example Link 2</a><br />
#   <a href="">Example Link 3</a>
#   </div> <!-- side -->
#
# On deck:
# <a href="$scriptname?post=1">Edit</a><p /><!-- requires post helper -->
#
# support external sidebar
# if the file doesn't exist, then useextside = 0
# if the file exists and is readable, then useextside = 1
# if the file exists and is not readable, then useextside = 2
$useextside = 0;
if ( @file_exists("$datadir/sidebar") ) {
    $useextside = 1;
    if ( @is_readable("$datadir/sidebar") ) {
	$useextside = 2;
    }
} else {
    $useextside = 0;
}
# print "$useextside"; #debug
if ( $useextside == 2 ) {
    require("$datadir/sidebar");
    extsidebar($scriptname);
} else {
print "<div id=\"side\">";
if ( $useextside == 1 ) {
    print "Error: You have an external sidebar, but it's unreadable.";
    print " Check permissions and see the help page for more information.<p />";
}
# ----- put your sidebar items between the div begin and div end tags
print <<<EOF
<strong>Menu</strong><p />
<a href="$scriptname">Home</a><br />
<a href="$scriptname?sa=1">Archives</a><br />
<a href="$scriptname?rc=1">Recent Comments</a><br />
<a href="$scriptname?f=rss">Syndicate (RSS 2.0)</a><p />
<form action="$scriptname" method="POST">
Search:<br />
<input type="text" class="fieldfont" name="searchstring" size="12">
<input class="buttfont" type="submit" name="ssubmit" value="ok">
</form>
<p />
<strong>Links</strong><p />
<a href="">Example Link 1</a><br />
<a href="">Example Link 2</a><br />
<a href="">Example Link 3</a>
</div> <!-- side -->
EOF;
# ----- put your sidebar items between the div begin and div end tags
}
## End User Config Zone, Pt. II ################################## 


## disallow example base url or stuff will break ##################
if ( preg_match ("/example/", $baseurl) ) {
    print "<div id=\"main\">\n";
    print "<div class=\"error\">\n";
print <<<EOF
Error:<p />You have
not set the baseurl!  Not setting the baseurl will cause
certain Agolbloga features to malfunction.<p />
Currently it is set to the example address ($baseurl), which
is the default, example baseurl. Please
edit the baseurl variable in the script so that it reflects the
path, relative to your DOCROOT, to the directory that contains the
Agolbloga script.  For example, if URL of your blog is
"http://www.example.com/blog/agolbloga.php", set baseurl to
"http://www.example.com/blog".
EOF;
   	print "</div>";
   	print "</div>";
	pad($padpad);
	exit;
}
## disallow example base url or stuff will break ##################


## disallow example email address if commail set ##################
if ( ( $commail ) &&
   ( preg_match ("/example.com/", $ownermail) ) 
   ) {
   	print "<div id=\"main\">\n";
   	print "<div class=\"error\">\n";
print <<<EOF
Error:<p />You have configured Agolbloga to send you an email whenever
you receive a new comment.  Good for you.  This is the best way to
catch comment spammers, and it's fun to see your new comments right
away.  HOWEVER, you have not configured your email address.
Currently it is set to the example address ($ownermail). Please
edit the ownermail variable in the script.
EOF;
   	print "</div>";
   	print "</div>";
	pad($padpad);
	exit;
}
## disallow example email address if commail set ##################


## permalink ######################################################
#
# if this is a permalink request, then do that and exit
#
$permafile = $_GET['arch'];
if ( isset($permafile) ) {
	showperma($scriptname, $permafile, $datadir, $baseurl);
	exit;
}
## permalink ######################################################



## archive listing ################################################
#
# if this is an archive listing, then do that and exit
#
$sa = $_GET['sa'];
if ( $sa ) {
	listarchive($scriptname, $permafile, $datadir, $baseurl,
	$maxarch, $padpad);
	exit;
}
## archive listing ################################################



## about Agolbloga ################################################
#
# if this is a request for the about page, show it and exit
#
$about = $_GET['about'];
if ( $about ) {
	showabout($scriptname, $baseurl);
	exit;
}
## about Agolbloga ################################################



## help ###########################################################
#
# if this is a request for the about page, show it and exit
#
$help = $_GET['help'];
if ( $help ) {
	showhelp($scriptname, $baseurl);
	exit;
}
## help ###########################################################



## new comment ####################################################
#
# if this is a new comment, then check the input and write to file
#
$newcomment = $_POST['newcomment'];
if ( preg_match("/Post/", $newcomment) ) {
	$cname = $_POST['cname'];
	$cemail = $_POST['cemail'];
	$curl = $_POST['curl'];
	$ccomment = $_POST['ccomment'];
	$permafile = $_POST['permafile'];
	newcomment($datadir, $scriptname, $baseurl, $permafile, $cname, $cemail, $curl, $ccomment, $ownermail, $commail);
	showperma($scriptname, $permafile, $datadir, $baseurl);
	#endpage($scriptname);
	exit;
}
## new comment ####################################################



## search #########################################################
#
# if this is a search request, start searching
#
$searchstring = $_POST['searchstring'];
if ( preg_match("/.+/", $searchstring) ) {
	search($datadir, $scriptname, $baseurl, $searchstring,
	$padpad);
	#endpage($scriptname);
	exit;
}
## new comment ####################################################



## recent comments ################################################
#
# if this is a recent comments request, do that
#
$rc = $_GET['rc'];
if ( $rc) {
    recentcomments($scriptname, $permafile, $datadir, $baseurl,
    $maxrc, $padpad);
    #endpage($scriptname);
    exit;
}
## new comment ####################################################


## no entries #####################################################
#
# if there are no current entries then assume this is a brand
# new installation and print a welcome message.  this is necessary
# because if you print nothing in the main area, the page looks ugly
# and will be the first thing a new user sees.  yuck.
#
# replace with scandir in php5
$dir2 = "$datadir";
$dh2  = opendir($dir2);
#files2count = 0;
while (false !== ($filename2 = readdir($dh2))) {
    if ( preg_match("/.txt$/", $filename2) ) {    
    	$files2count++;
    }
}
if ( $files2count < 1 ) {
print <<<EOF
<div id="main">
<div class="posttitle">Success!</div>
<div class="postbody">
<p />
You have successfully installed Agolbloga!  
<p />
You can now start posting new blog entries.  To learn how to use
Agolbloga, please see the <a href="$scriptname?help=1">Agolbloga help page</a>.
<p />
Remember, you can always get back to the Agolbloga help page by
following the "powered by Agolbloga" link at the bottom of any
Agolbloga page.  This will take you to--surprise!--the Agolbloga
"about" page, which, in turn, will have a link to the Agolbloga help
page.  
<p />
If you have feedback about the installation in particular or
Agolbloga in general, feel free to visit
<a href="http://www.briantanaka.com/agolbloga">the Agolbloga website</a>
<p />
This message will vanish once you start posting.
</div> <!-- postbody -->
</div> <!-- main -->
EOF;
pad($padpad);
endpage($scriptname);
exit;
}
#
## no entries #####################################################



###################################################################
## main page begin ################################################


#
# get array of posts
# (use scandir in php5)
#
print "\n<div id=\"main\">\n";
$dir = "$datadir";
$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
    $modtime = filemtime("$datadir/$filename");
    $combo = "$modtime" . ":" . "$filename";
    $files[] = $combo;
}
# sort them, reverse chronologically (standard blog order)
rsort($files);


#
# go through all the files and directories in the 
# datadir and print anything ending in .txt
#
$padcount = 0;
foreach ( $files as $i) {
    $commentcount = 0;
    if ( preg_match("/\.txt$/", $i) ) {
	$padcount++;
	print "\n    <div class=\"box1\">\n";
    	#print "$i\n"; #debug
	list($date, $name) = split(":", $i);

	# count the number of comments
	if ( is_readable ("$datadir/archive/$name.comments") ) {
	    if ( $lines = file("$datadir/archive/$name.comments") ) {
		$commentcount = 0;
	        foreach ( $lines as $curline ) {
		    if ( preg_match("/-=-=-=-=-=/", $curline) ) {
		        $commentcount++;
		    }
		}
	    }
	}

	if ( ! $file = @fopen ("$datadir/$name", "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;
	    while (!feof($file)) {
		$count++;
		$string = fgets($file, 4096);
		$trimmed = rtrim($string);
		if ( $count ==1 ) {
		    print "\n<p />\n"; # makes links lynx happy
		    print "    <div class=\"posttitle\">$trimmed</div>\n";
		    print "    <div class=\"postbody\">";
		} else {
		    print "$string";
		}
	    }
	    print "    </div> <!-- postbody -->\n";
	    $pdate = date("l F j, Y - g:i a ", $date);
	    print "    <div class=\"postfoot\">Posted $pdate\n";
	    print "\n - <a";
	    print " href=\"$baseurl/$scriptname?arch=$name\">Permalink</a>";
	    print "\n - <a";
	    print " href=\"$baseurl/$scriptname?arch=$name\">Comment</a>";
	    print " ($commentcount)\n";
	    print "</div> <!-- postfoot -->\n";
	}
	print "    </div> <!-- box1 -->\n";
    }
}
print "\n</div> <!-- main --> \n";



#
# make permalink copies 
#
reset($files);
#print_r($files);
foreach ( $files as $i) {
    # see if its there
    list($date, $name) = split(":", $i);
    if ( ( preg_match("/.txt$/", $name) ) &&
    ( file_exists("$datadir/archive/$name") ) ) {
        # check filesizes.  if theyre the same then move on.
	# if theyre not, then warn and continue
	$old = filesize("$datadir/archive/$name");
	$new = filesize("$datadir/$name");
	#print " $new $old";
	if ( ! ($old == $new) ) {
	    print "\n<div class=\"error\">\n";
print <<<EOF
Warning:
Agolbloga has found a previously archived post with the same name 
as $name but of a different size!  This means, either: a) you have
edited a previously archived post, or b) you're using the same
filename for a new post as an older, different post.  In the case of
'a', simply delete the archived $name, and reload this page.  In the
case of 'b', rename the new post, and reload this page.
For now, Agolbloga will skip archiving the new post, so be
advised that the permalink will be wrong until you've remedied
the problem. 
EOF;
	    print "</div>\n";
	}
    } else {
	if ( preg_match("/.txt$/", $name) )  {
	    #print "copying $name";
	    if ( ! copy("$datadir/$name", "$datadir/archive/$name") ) {
	        print "error: failed to copy $name...<br />\n";
	    }
	}
    }
}

# kludge to prevent 'lolling tongue problem'
if ( $padcount < 3 ) {
    pad($padpad);
}

#
# print the html footer stuff
#
endpage($scriptname);

## main page end ##################################################
###################################################################




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

# ---------------------------------------------------------------------
function startpage($title, $subtitle, $datadir) {
print <<<EOF
<html>
<head>
<title>$title</title>
<style type="text/css">
EOF;

#
# support external stylesheet / theme
#
if ( @file_exists("$datadir/style.css") ) {
    if ( ! $file = @fopen ("$datadir/style.css", "r") ) {
	print "error: could not open style!\n";
	exit;
    } else {
        fpassthru($file);
    }
    fclose($file);
} else {

print <<<EOF

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 {
    width: 725px;
    padding: 0px 0px 0px 0px;
    margin-top: 20px;
    margin-left: 20px;
    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.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 0px 0px 18px; 
    margin: 0px 30% 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 10px 0px;
}
div.postbody {
    border: 0px solid black;
    line-height: 1.5em;
    /* border: 1px dashed red; */
}
div.postfoot {
    border-top: 0px dashed #000;
    font-size: 10px;
    margin: 10px 0px 20px 0px;
    text-align: left;
}
div#byme {
    width: 725px;
    padding: 0px 0px 0px 0px;
    margin-top: 4px;
    margin-left: 20px;
    font-size: 0.85em;
    text-align: right;
}
div.ital {
    font-family: sans-serif;
    font-style: italic;
    border: 1px dashed #000;
    padding: 8px 8px 8px 8px;
    background: #dfdfdf;
    font-size: 14px;
}
div.footnotes {
    border-top: 1px dashed #000;
    padding: 8px 0px 0px 0px;
    margin: 8px 0px 0px 0px;
    font-style: italic;
}
div.commentbox {
    border: 1px dashed #666;
    padding: 8px 8px 8px 8px;
    margin: 8px 8px 8px 0px;
}
.fieldfont {
    font-family: sans-serif;
    font-size: 12px;
}
.buttfont {
    font-family: sans-serif;
    font-size: 12px;
}
EOF;
}

print <<<EOF
</style>
</head>
<body>
<div id="outerbox">
<div id="blogtitle">
    $title
    <div id="blogsubtitle">$subtitle</div>
</div>
EOF;
}

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

# ---------------------------------------------------------------------
function isdatadir($datadir) {
if ( ! is_readable($datadir) ) {
    print "\n<div class=\"error\">\n";
    print "Agolbloga error:<p />";
    print "The datadir you defined ($datadir)";
    print " is not readable by the owner of the ";
    print " webserver process or does not exist.";
    print " You must create $datadir,";
    print " fix the permissions settings of $datadir, or adjust the";
    print " the datadir variable before Agolbloga will work.";
    print "<p />If you haven't done so, please read the 'installation'";
    print " section of the Agolbloga script.";
    print " It's short and will help you get started quickly.";
    print " \n</div>\n";
    endpage($scriptname);
    exit;
}
}

# ---------------------------------------------------------------------
function isarchivedir($archivedir) {
if ( ! is_writeable($archivedir) ) {
    print "\n<div class=\"error\">\n";
    print "Agolbloga error:<p />";
    print "The archive directory ($archivedir) is not writeable";
    print " by the httpd process or does not exist.";
    print "<p />If you haven't done so, please read the 'installation'";
    print " section of the Agolbloga script.";
    print " It's short and will help you get started quickly.";
    print " \n</div>\n";
    endpage($scriptname);
    exit;
}
}

# ---------------------------------------------------------------------
function showperma($scriptname, $permafile, $datadir, $baseurl) {
print <<<EOF
<div id="main">
<div class="box1">
EOF;
#
# double dot defeat
#
if ( preg_match("/\.\./", $permafile) ) {
	print "<div class=\"error\">Illegal URL</div>\n";
	exit;
}
if ( ! $file = @fopen ("$datadir/archive/$permafile", "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=\"posttitle\">$string</div>";
	    print "<div class=\"postbody\">";
	} else {
	    print "$string";
	}
    }
    print "</div> <!-- postbody -->\n";
    $date = filemtime("$datadir/archive/$permafile");
    $pdate = date("l F j, Y - g:i a ", $date);
    print "<div class=\"postfoot\">Posted $pdate";
    print "\n - <a";
    print " href=\"$baseurl/$scriptname?arch=$permafile\">Permalink</a>\n";
    #print "\n - <a";
    #print " href=\"$baseurl/$scriptname?arch=$permafile\">Comment</a>";
    print "</div>\n";

#
# show comments and make form for new
#
if ( is_readable ("$datadir/archive/$permafile.comments") ) {
    if ( $lines = file("$datadir/archive/$permafile.comments") ) {
	$commentcount = 0;
	#print_r($lines);
	print "\n<p />\n<div class=\"commentbox\">";
	foreach ( $lines as $curline ) {
	    #print "$curline"; #debug

	    if ( preg_match("/agolbloga_date/", $curline) ) {
	        list($label, $value) = split("~", $curline);
		$chopped = chop($value);
		print "On $chopped,<br />\n";
		continue;
	    }

	    if ( preg_match("/agolbloga_name/", $curline) ) {
	        list($label, $value) = split("~", $curline);
		print "$value";
		continue;
	    }

	    if ( preg_match("/agolbloga_email/", $curline) ) {
	        list($label, $value) = split("~", $curline);
		if ( preg_match("/.+/", $value) ) {
		    print "(<a href=\"mailto:$value\">email</a>) ";
		}
		continue;
	    }

	    if ( preg_match("/agolbloga_url/", $curline) ) {
	        list($label, $value) = split("~", $curline);
		if ( preg_match("/.+/", $value) ) {
		    print " (<a href=\"$value\">website</a>)";
		}
		print " commented:<p />\n";
		continue;
	    }

	    if ( preg_match("/agolbloga_remip/", $curline) ) {
	        list($label, $value) = split("~", $curline);
		if ( preg_match("/.+/", $value) ) {
		    print "<!-- $value -->\n";
		}
		continue;
	    }

	    if ( preg_match("/-=-=-=-=-=/", $curline) ) {
		print "</div> <!-- commentbox -->";
		print "<div class=\"commentbox\">";
		$commentcount++;
		continue;
	    }

	    if ( preg_match("/agolbloga_comment~/", $curline) ) {
		continue;
	    }

	    print $curline;

	}
	print "$commentcount comments so far.\n";
	print "</div> <!-- commentbox -->";
    }
}
# make form for new
print <<<EOF
<p />
<form method="post" action="$scriptname">
<p />
Post a new comment...
<p />
<input type="text" class="fieldfont" name="cname"> name <p />
<input type="text" class="fieldfont" name="cemail"> email (optional)<p />
<input type="text" class="fieldfont" name="curl"> url (optional)<p />
<textarea class="fieldfont" name="ccomment" rows="8" cols="50">
</textarea>
<p />
<input type="hidden" name="datadir" value="$datadir">
<input type="hidden" name="permafile" value="$permafile">
<input class="buttfont" name="newcomment" type="submit" value="Post">
</form>
EOF;

print <<<EOF
</div> <!-- box1 -->
</div> <!-- main -->
</div> <!-- yet another stupid ie workaround -->
EOF;
}
endpage($scriptname);
}

# ---------------------------------------------------------------------
function listarchive($scriptname, $permafile, $datadir, $baseurl,
$maxarch, $padpad) {
#
# get array of posts
# (use scandir in php5)
#
print "\n<div id=\"main\">\n";
# print "<a href=\"$scriptname\">Home</a>";
print "<p />";
print "<div class=\"posttitle\">Last $maxarch Archived Posts</div>\n";
print "<p />";
$dir = "$datadir/archive";
$dh  = opendir($dir);
$padcount = 0;
while (false !== ($filename = readdir($dh))) {
    $modtime = filemtime("$datadir/archive/$filename");
    $combo = "$modtime" . ":" . "$filename";
    if ( preg_match("/.txt$/", $combo) ) {
	$padcount++;
	$files[] = $combo;
    }
}
if ( empty($files) ) {
print <<<EOF
<div class="postbody">
There are no archived posts.
</div>
EOF;
pad($padpad);
exit;
}
# 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 > $maxarch ) {
    	break;
    }
    list($date, $name) = split(":", $i);
    if ( ! $file = fopen ("$datadir/archive/$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\">$string</div>";
	    }
	}
	$pdate = date("l F j, Y - g:i a ", $date);
	print "<div class=\"postfoot\"> - Posted $pdate";
	print " - <a href=\"$baseurl/$scriptname?arch=$name\">Permalink</a></div>\n";
    }
}
print "\n</div>\n";
# kludge to prevent 'lolling tongue problem'
if ( $padcount < 3 ) {
    pad($padpad);
}
endpage($scriptname);
}

# ---------------------------------------------------------------------
function rss($scriptname, $permafile, $datadir, $baseurl, $maxarch,
$title, $subtitle) {

header('Content-type: application/xml');
header('Content-Disposition: attachment; filename="agolbloga.xml"');

$dater = date(r);

print <<<EOF
<?xml version="1.0" ?>
<rss version="2.0">

<channel>

<title>$title</title>
<description>$subtitle</description>
<link>$baseurl/$scriptname</link>
<pubDate>$dater</pubDate>
<language>en-us</language>
<generator>Agolbloga v0.1</generator>

EOF;

#
# get array of posts
# (use scandir in php5)
#
# print "foo\n";
# print "<p />\n";
$dir = "$datadir";
$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
    $modtime = filemtime("$datadir/$filename");
    $combo = "$modtime" . ":" . "$filename";
    $files[] = $combo;
}
# sort them, reverse chronologically (standard blog order)
rsort($files);

#
# go through all the files and directories in the 
# datadir and print anything ending in .txt
#
foreach ( $files as $i) {
    if ( preg_match("/\.txt$/", $i) ) {
    	#print "$i\n"; #debug
	print "\n<item>\n";
	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);
		$trimmed = rtrim($string);
		if ( $count ==1 ) {
		    print "<title>$trimmed</title>\n";
		    print "<description><![CDATA[";
		} else {
		    print "$string";
		}
	    }
	    print "]]></description>\n";
	    #$pdate = date("l F j, Y - g:i a ", $date);
	    #print "\nPosted $pdate\n";
	    print "<link>$baseurl/$scriptname?arch=$name</link>\n";
	}
	#print "    </div> <!-- box1 -->\n";
	print "</item>\n\n";
    }
}
#print "\n</div> <!-- main --> \n";
#print "</pre>";
print <<<EOF
</channel>
</rss>
EOF;
}


# ---------------------------------------------------------------------
function showabout($scriptname, $baseurl) {
print <<<EOF
<div id="main">
<div class="box1">
<div class="posttitle">About Agolbloga
</div><div class="postbody">
<p />
<div class="ital">
Agolbloga (ah goal BLAH gah), n. - A simple, lightweight blogging
engine written in PHP.
</div>
<p />
The goal of the Agolbloga project is to create
a simple, lightweight blogging engine with
all of the requisite features of a full-fledged blogging system but
implemented in a single PHP script.[1]
<p />
For help with Agolbloga, please see
<a href="$scriptname?help=1">the Agolbloga help page</a>.
<p />
Currently, Agolbloga has the following features:
<ul>
<!-- <li>Standard (most-recent in reverse-chronological order) post
display on m
ain page -->
<li>Integrated commenting system
<li>Comment spam blacklisting/blocking
<li>Integrated "help" documentation
<li>Outbound RSS feed
<li>Archive browsing
<li>Permalinks
<li>W3C standards compliance
<li>A selection of pre-made styles (aka "themes" or "skins")
<li>Search
<li>Easy installation
</ul>
<p />
Potential future features include:
<ul>
<li>Form-based posting. (Maybe.)
</ul>
<p />
For more Agolbloga fun, please feel free to visit
<a href="http://www.briantanaka.com/agolbloga">the Agolbloga website</a>.
EOF;

print <<<EOF
<p />
&nbsp; &nbsp; &nbsp; -- Brian Tanaka, brian@briantanaka.com
<p />
<div class="footnotes">
[1] Aside from being written in PHP rather than Perl,
the general aim of the
project is not unlike another single-script blogging engine:
Blosxom.  However, this is not a Blosxom re-implementation...
for better or worse! Any similarities in the code are
coincidental.
</div> <!-- footnotes -->
</div> <!-- postbody -->
</div> <!-- box1 -->
</div> <!-- main -->
EOF;
endpage($scriptname);
}

# ---------------------------------------------------------------------
function showhelp($scriptname, $baseurl) {
print <<<EOF
<div id="main">
<div class="box1">
<p />
<div class="posttitle">Welcome to the Agolbloga help page</div>
<div class="postbody"> <p />
This is a short guide to using Agolbloga.  Since Agolbloga is
intended for a slightly-more-sophisticated-than-average user, a fair
amount of prior knowledge about the Internet, web servers, FTP, Unix
file permissions, basic filesystem commands,
and so on is assumed.  However, don't let that
scare you if you're a novice.  I think you'll find using Agolbloga
quite easy.
<p />
Note: If you would like to use a friendlier interface, try
Agoladmin.  Agoladmin is the GUI interface for Agolbloga and is
available on the Agolbloga website which you can reach via the
<a href="$scriptname?about=1">about page</a>.  <strong>The
instructions below assume you are not using Agoladmin</strong>.
<p />
Topics:
<ol>
<li><a href="#installation">Installation</a>
<li><a href="#upgrading">Upgrading (Read even if you're not
upgrading!)</a>
<li><a href="#extconfig">External Configuration Files</a>
<li><a href="#adddelete">Adding And Deleting Posts</a>
<li><a href="#edit">Editing Posts and An Important Warning About Filenames</a>
<li><a href="#sidebar">Adding Stuff To The Sidebar</a>
<li><a href="#search">Search Tips</a>
<li><a href="#css">Changing Cascading Stylesheets (CSS)</a>
<li><a href="#outboundrss">Outbound RSS</a>
<li><a href="#blacklist">Comment Blacklisting (Spam Prevention)</a>
<li><a href="#padpad">Preventing Over-extended Sidebar</a>
</ol>
</div> <!-- postbody -->

<a name="installation"></a>
<div class="posttitle">Installation</div>
<div class="postbody"> <p />
I assume you've already mastered installing Agolbloga or else you
wouldn't be seeing this page!  However, if you need help installing
Agolbloga, please read the "readme" section of the script itself.
That's where the latest installation information is kept.  Also, you
should definitely read the "Upgrading" section because it gives tips
on configuring Agolbloga now that will help you upgrade later.
</div> <!-- postbody -->

<a name="upgrading"></a>
<div class="posttitle">Upgrading (Read even if you're not
upgrading!)</div>
<div class="postbody"> <p />
Upgrading Agolbloga is as easy as replacing the current script with
the new version.  However, it's a good idea to make a copy of the
current script first, just in case something unexpected happens.
Additionally, you should consider using an external configuration
file and an external sidebar file.  (See the "External Configuration
Files" and "Adding Stuff To The Sidebar" sections.)  If you feel the
urge to make CSS changes, use an external CSS file.  (See "Changing
Cascading Stylesheets (CSS)".)  Using these external files will
minimize the number of customizations you'll have to re-do when you
upgrade.
</div> <!-- postbody -->

<a name="extconfig"></a>
<div class="posttitle">External Configuration Files</div>
<div class="postbody"> <p />
You should configure Agolbloga by editing the "User Config
Zone, Pt. I" and "User Config Zone, Pt. II" sections
of the Agolbloga script. 
<p />
However, a better approach is to use an "externalized" config file.
If you keep
your config settings in an external file, you'll only need to set
the datadir variable when you upgrade.
<p />
To use an externalized config file, simply 
create a file named "config" in your datadir. Make sure
the webserver can read it!
<p />
Here's a sample "config" file:

<pre>
&lt;?php
#function config() {

# Set the title and subtitle of your blog
&#36;title = "Ext Example Blog";
&#36;subtitle = "The Agolbloga example blog...";

# Specify where you will store your posts.  This directory
# must be in the document root because a subdirectory of it
# will contain the permalinked archive copies of posts.
&#36;datadir = "./agolbloga.data";

# What's the base url of this Agolbloga installation?
&#36;baseurl = "http://127.0.0.1/sandiegosession/agolbloga";

# Number of entries to list in default archive browse list
&#36;maxarch = 100;

# Number of recently commented posts to show in recent comments
&#36;maxrc = 12;

# If you want to receive an email every time someone comments,
# then set commail to 1.  Otherwise, set it to zero.

# I recommend setting this to 1 so that you can catch comment
# spammers more quickly.
# If you set it to 1, you must also set your email address in
# ownermail.
&#36;commail = 1;

# Your email address
&#36;ownermail = "blogperson@example.com";

# Set this to the number of pixels with which to pad short pages.
&#36;padpad = 200;

# If you have installed any Agolbloga helpers, specify the directory
# where they are installed here.
#&#36;helperdir = "./agolbloga.helpers";

#}
?>
</pre>
</div> <!-- postbody -->

<a name="adddelete"></a>
<div class="posttitle">Adding And Deleting Posts</div>
<div class="postbody"> <p />
(Note: These instructions assume you are not using Agoladmin, the
GUI interface for Agolbloga.  See the blurb about it at the top of
this page.) <p />
To create a new post create a text file in your datadir.
If you have shell access, you can edit right there.
If you only have FTP access, you can edit your post
on your local machine and FTP it to the remote datadir.
<p />
Only files ending in .txt will be considered posts.
So, name your file like this: "foobar.txt".  Bear in mind, however,
that you must never use the same filename for two different posts
for reasons you'll see in the "Editing Previously Saved Posts"
section of this page.  For that reason, it's best to use names that
are likely to be unique.  I recommend including the date in the filename.
For example: "040902.foobar.txt".  
(Note: If you are using or plan on using Agoladmin, the GUI
interface to Agolbloga, you must use Unix timestamps as filenames.
For example: 1094829882.txt.)
<p />
The format of your file should be as follows:
<ul>
<li>The first line is the title of your post.
<li>All subsequent lines are the body of your post.
<li>Use &lt;p /> between paragraphs.
</ul>
<p />
Since the permalinks for your posts always point to the archive
directory, you can safely remove postings from the datadir.
Deleting a file from your datadir 
will make the deleted post vanish from the main page of your blog,
but it will live on in your archive.
For instance, if you only want to show the latest three posts
on your main page,
simply delete all but the latest three.  
<p />
Because permalinks point to the archive directory, however, if you
want to completely remove a post from your blog, remember to
delete
it from your archive directory as well.
<p />
NOTE: A simple shell script called mkpost has been included at the
end of the agolbloga script.  If you're familiar with shell scripts
and would like one that makes new posts with (almost certainly) unique
filenames, then use mkpost.
</div> <!-- postbody -->

<a name="edit"></a>
<div class="posttitle">Editing Posts and An Important Warning About
Filenames</div>
<div class="postbody"> <p />
When you edit a post in the datadir--in other words, a 
post currently displayed on the main page--you need to tell Agolbloga how
to resolve the difference between the current version and the
archived version.  The reason for this is that Agolbloga prevents
you from
accidentally giving two different posts the same filename.  In the
archive, all posts must have unique filenames, just the way all
files in a directory or folder on your computer must have unique
filenames.  If Agolbloga happily archived a copy of a different file
with the same name, the old file would be lost forever, and we
wouldn't want that, would we?
(Again, it's best to use names that are likely to be unique. I
recommend including the date in the filename. For example:
"040902.foobar.txt".)
(Note: If you are using or plan on using Agoladmin, the GUI
interface to Agolbloga, you must use Unix timestamps as filenames.
For example: 1094829882.txt.)
<p />
If Agolbloga finds an archived post of a
different size but with the same name as a current post, you have
two choices:
<p />
<ol>
<li>If you are simply changing a current post in the datadir, then
delete the old archived version from the archive directory and
reload the main page.  A new archived version will be created and
all is well.
<p />
<li>If you have mistakenly given a new post the same name as an old
post, then you must rename the new post.
</ol>
<p />
Agolbloga will not
overwrite a file with the same name if the sizes are different.
Rather it will print an error and continue.  As stated in the error
message, the permalink for the problem post will be incorrect until
you fix the problem.
<p />I realize this sounds a bit complicated, but it's not once you
try it.  I also realize that a more user-friendly solution may be in
order.  
</div> <!-- postbody -->

<a name="sidebar"></a>
<div class="posttitle">Adding Stuff To The Sidebar</div>
<div class="postbody"> <p />
You can customize the right sidebar by editing the "User Config
Zone, Pt. II" section of the Agolbloga script.  Example links are
supplied, but you may do whatever you like to it.
<p />
A better approach is to use an "externalized"
sidebar.  If you keep your sidebar html in an external file, you
won't need to edit the sidebar part of the script when you upgrade.
<p />
To use an externalized sidebar, simply put everything you'd
like in your sidebar in a file named "sidebar" in your datadir.
Make sure the webserver can read it!  And that's it.  Agolbloga will
use the external sidebar if it finds it.
<p />
<!-- sasquatch -->
Here's a sample "sidebar" file:
<pre>
&lt;?php
function extsidebar (&#36;scriptname) {
# ----- put your sidebar items between the div begin and div end tags
print &lt;&lt;&lt;EOF
&lt;div id="side">
ext.&lt;br />
&lt;strong>Menu&lt;/strong>&lt;p />
&lt;a href="&#36;scriptname">Home&lt;/a>&lt;br />
&lt;a href="&#36;scriptname?sa=1">Archives&lt;/a>&lt;br />
&lt;a href="&#36;scriptname?rc=1">Recent Comments&lt;/a>&lt;br />
&lt;a href="&#36;scriptname?f=rss">Syndicate (RSS 2.0)&lt;/a>&lt;p />
&lt;form action="&#36;scriptname" method="POST">
Search:&lt;br />
&lt;input type="text" class="fieldfont" name="searchstring" size="12">
&lt;input class="buttfont" type="submit" name="ssubmit" value="ok">
&lt;/form>
&lt;p />
&lt;strong>Links&lt;/strong>&lt;p />
&lt;a href="">Example Link 1&lt;/a>&lt;br />
&lt;a href="">Example Link 2&lt;/a>&lt;br />
&lt;a href="">Example Link 3&lt;/a>
&lt;/div> &lt;!-- side -->
&#69;OF;
}
?>
</pre>
</div> <!-- postbody -->

<a name="search"></a>
<div class="posttitle">Search Tips</div>
<div class="postbody"> <p />
The built-in search function is very simple and therefore rather
limited.  It will search for the exact phrase typed in the search
form.  No more.  No less.  For instance, if you search for "foo
bar", it will look for "foo bar", not posts with both the word foo
and bar in it (as you may be used to from search engines such as
Google).  Speaking of Google, if you'd rather use a site specific
Google search dialog instead of the built-in search function, you
may of course do so.  Finally, note that searches cannot contain
certain characters (e.g. "/").
</div> <!-- postbody -->

<a name="css"></a>
<div class="posttitle">Changing Cascading Stylesheets (CSS)</div>
<div class="postbody"> <p />
Agolbloga has a default stylesheet that is perfectly suitable for
most purposes.  You need do nothing to activate it; it's used
automatically.
<p />
However, you can change the way your blog looks by changing the
stylesheet.  There are two ways to do this.  Both will work, but
only one is recommended.  The bad way is to edit the stylesheet in
the Agolbloga script itself.  This will work perfectly well, but
when you upgrade Agolbloga, you'll have to make all those style
changes again.  Not fun!
<p />
The better way is to take advantage of Agolbloga's external
stylesheet scheme.  Agolbloga will use the stylesheet called
"style.css" in your datadir, if that file exists.  If it doesn't, it
simply uses the default.
<p />To get you started, there are a number of sample alternate
stylesheets on the Agolbloga website.  Get one and save it
as style.css in your datadir.  (Don't forget to make it world
readable!)  You may now edit that stylesheet to your heart's
content.
<p />Note that using style.css has another advantage.  Namely, you
can use style.css as the stylesheet for any other auxilary pages on
your site, and all your pages, including your blog, will have a
consistent look and feel.  Consult the stylesheet itself for class
and id names.
</div> <!-- postbody -->

<a name="outboundrss"></a>
<div class="posttitle">Outbound RSS</div>
<div class="postbody"> <p />
Agolbloga automatically creates an outbound Rich Site Summary (RSS
2.0) feed.  A link to the feed is one of the standard, default
sidebar items.  In case you don't have the default sidebar items for
some reason, the magic incantation for the feed is to append
"?f=rss" to the end of the base Agolbloga URL on your site.  (eg.
http://www.example.com/agolbloga.php?f=rss)
</div> <!-- postbody -->

<a name="blacklist"></a>
<div class="posttitle">Comment Blacklisting (Spam Prevention)</div>
<div class="postbody"> <p />
Spammers like to place bogus comments in people's blogs.  They do
this so that Google and other
search engines will count the comment as an inbound link to
their site.  If not evil, it's, at the very least, annoying.  You
can prevent spammers (and other people you don't like) from
commenting in your Agolbloga blog by "blacklisting" their IP
addresses.  It's very simple.  Simply create a file, readable by the
webserver, called "blacklist" in your datadir.  In that file, list
the IP addresses you would like to block, one IP address per line.
<p />
You can find the spammer's IP address by inspecting the comments
file corresponding to the defaced post.  For instance, if the
filename of the defaced post is "040808.115353.txt" then
the comments file is "040808.115353.txt.comments".  The IP address
is also printed as a comment in the web view of the post.  Use the
"View Source" function of your web browser to find the IP address.
</div> <!-- postbody -->

<a name="padpad"></a>
<div class="posttitle">Preventing Over-extended Sidebar</div>
<div class="postbody"> <p />
If you put a lot of items in your sidebar, it may at times extend
beyond the main part of the page.  You can control how much padding
is added to the bottom of short main pages by changing the value of
the padpad setting in the Agolbloga script (or external config, if
you are using one.)
</div> <!-- postbody -->

</div> <!-- box1 -->
</div> <!-- main -->
</div> <!-- spare off div -->
EOF;
endpage($scriptname);
}


# ---------------------------------------------------------------------
function newcomment($datadir, $scriptname, $baseurl, $permafile, $cname, $cemail, $curl, $ccomment, $ownermail, $commail ) {
# print " - $datadir, $permafile, $cname, $cemail, $curl, $ccomment, $permafile -\n"; #debug

#
# blacklist
#
$ip = $_SERVER["REMOTE_ADDR"];
#print "$ip";
if ( ! $file = @fopen ("$datadir/blacklist", "r") ) {
    #print "error: could not open blacklist. continuing...!\n";
    #exit;
} else {
    $count = 0;
    while (!feof($file)) {
	$string = fgets($file, 4096);
	if ( preg_match("/$ip/", $string) ) {
print <<<EOF
<div id="main">
<div class="box1">
<div class="posttitle">
You have been blacklisted for spamming!  
</div>
<div class="postbody">
<p />
If you feel you have been blacklisted in error, please contact the
owner of this blog.
<p />
If, on the other hand, you really are a spammer, how do you sleep at
night?  Doesn't it bother you that by comment spamming, you lower
yourself to a moral and ethical level only just barely higher than
child molester?  Can't you find a way to make a living without
becoming a subhuman parasite?  Are you that pathetic?  Think about
it.
<p />
You only have one life to live, and you're blowing it.  You're
robbing yourself of your own dignity.  (And annoying the rest of
us.)
<p />
&nbsp; &nbsp; &nbsp; -- Agolbloga
</div> <!-- postbody -->
</div> <!-- box1 -->
</div> <!-- main -->
EOF;
	    endpage($scriptname);
	    exit;
	}
    }
}
@fclose($file);

#
# check for required fields
#
$errcount = 0;
if ( ! preg_match("/.+/", $cname) ) { $errcount++; }
if ( ! preg_match("/.+/", $ccomment) ) { $errcount++; }
if ( $errcount > 0 ) {
print <<<EOF
<div class="error">
Agolbloga Error:<p />
You must supply at least a name and a comment.  The email and URL
fields are optional.  
</div>
EOF;
showperma($scriptname, $permafile, $datadir, $baseurl);
endpage($scriptname);
exit;
}

# get the date
$agolbloga_date = date("l F j, Y - g:i a ");

# build the final comment string
$stripped = strip_tags($ccomment);
$comstring =
"agolbloga_date~" .
"$agolbloga_date" .
"\n" .
"agolbloga_name~" .
"$cname" . 
"\n" .
"agolbloga_email~" .
"$cemail" .
"\n" .
"agolbloga_url~" .
"$curl" .
"\n" .
"agolbloga_remip~" .
"$ip" .
"\n" .
"agolbloga_comment~" .
"\n" .
"$stripped" .
"\n" .
"-=-=-=-=-=\n";

# in php5 use file_put_contents
# open for appending
# write new comment 
# close file
$permacomm = "$permafile" . ".comments";
if ( ! $file = fopen ("$datadir/archive/$permacomm", "a") ) {
    print "error: could not open blurb!\n";
    exit;
} else {
    if ( fwrite ($file, $comstring) === FALSE ) {
	print "Cannot write to file!\n";
    }
}
fclose($file);

#
# if user wants it, send email alert
#
if ( $commail ) {
    #print ">>> commail!"; #debug
    mail ( $ownermail,
	"New Blog Comment (Agolbloga)",
	"The following data has been added to $permacomm:\n\n$comstring"  );
}

}




# ---------------------------------------------------------------------
function search($datadir, $scriptname, $baseurl, $searchstring,
$padpad) {
#
# get array of posts
# (use scandir in php5)
#
print "\n<div id=\"main\">\n";
# print "<a href=\"$scriptname\">Home</a>";
#
# disallow slashes
#
if ( preg_match("/\//", $searchstring) ) {
print <<<EOF
<div class="error">
Error:
<p /> Search terms cannot contain a / (slash)
<p />Try adjusting your search term.  Remember that this is a very simple
search mechanism and searches for the exact string you specify.  (No
booleans, multiple non-adjoining terms, et cetera.)
<p /> Thank you.
<p /><br />
</div>
</div>
EOF;
endpage($scriptname);
exit;
}
print "<p />";
print "<div class=\"posttitle\">Search results for \"$searchstring\"</div>\n";
print "<p />";
$dir = "$datadir/archive";
$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
    $modtime = filemtime("$datadir/archive/$filename");
    $combo = "$modtime" . ":" . "$filename";
    if ( preg_match("/.txt$/", $combo) ) {
	$files[] = $combo;
    }
}
# sort them, reverse chronologically (standard blog order)
rsort($files);
reset($files);
# open each file, and print the title as a link
$foreachcount = 0;
$hitcount = 0;
foreach ( $files as $i) {
    $foreachcount++;
    list($date, $name) = split(":", $i);
    if ( ! $file = fopen ("$datadir/archive/$name", "r") ) {
	print "error: could not open blurb!\n";
	exit;
    } else {
	$count = 0;
	while (!feof($file)) {
	    $count++;
	    $string = fgets($file, 4096);
	    if ( $count == 1 ) {
		$titlestring = $string;
		# count for whether the title has been printed or not
		$titlecount = 0; 
	    }
	    #print "($string)\n"; #debug
	    if ( preg_match("/$searchstring/", $string) ) {
		$hitcount++;
		$titlecount++;
		if ( $titlecount == 1 ) {
		    print "<div class=\"posttitle2\">$titlestring</div>";
		}
	    	print "$string";
	    }
	}
	#$pdate = date("l F j, Y - g:i a ", $date);
	#print "<div class=\"postfoot\">Posted $pdate";
	#print "<div class=\"postfoot\">Posted $pdate";
	# if the title was printed, then a match was found
	if ( $titlecount > 0 ) {
	    print "<div class=\"postfoot\">\n";
	    print "<a href=\"$baseurl/$scriptname?arch=$name\">Permalink";
	    print "</a></div>\n";
	}
    }
}
print "$hitcount matches found\n";
if ( $hitcount == 0 ) {
print <<<EOF
<p />
Unfortunately, $searchstring was not found anywhere in this blog.
<p />
Try adjusting your search term.  Remember that this is a very simple
search mechanism and searches for the exact string you specify.  (No
booleans, multiple non-adjoining terms, et cetera.)
EOF;
}
print "\n</div>\n";
if ( $hitcount < 3 ) {
    pad($padpad);
}
endpage($scriptname);
}


# ---------------------------------------------------------------------
function recentcomments($scriptname, $permafile, $datadir, $baseurl,
$maxrc, $padpad) {
#
# get array of posts
# (use scandir in php5)
#
print "\n<div id=\"main\">\n";
# print "<a href=\"$scriptname\">Home</a>";
print "<p />";
print "<div class=\"posttitle\">Posts with recent comments</div>\n";
print "<p />";
$dir = "$datadir/archive";
$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
    $modtime = filemtime("$datadir/archive/$filename");
    $combo = "$modtime" . ":" . "$filename";
    if ( preg_match("/.txt.comments$/", $combo) ) {
	$files[] = $combo;
    }
}
# its possible for this array to be empty which means you should skip
$filescount = count($files);
if ( $filescount < 1 ) { 
    print "There don't seem to be any comments yet!";
    pad($padpad);
    print "</div>";
    endpage($scriptname);
    exit;       
}       
# 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 > $maxrc ) {
    	break;
    }
    list($date, $name) = split(":", $i);
    # get the non comment version of the name so we can get the
    # title out of the post
    #print "$name"; #debug;
    $match = ( preg_match("/(.+)\.comments/", $name, $matches) );
    #print " - $matches[1]"; #debug
    #if ( ! $file = fopen ("$datadir/archive/$name", "r") ) {
    if ( ! $file = fopen ("$datadir/archive/$matches[1]", "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\">$string</div>";
	    }
	}
	$pdate = date("l F j, Y - g:i a ", $date);
	print "<div class=\"postfoot\">Last comment $pdate";
	print " - <a href=\"$baseurl/$scriptname?arch=$matches[1]\">Permalink</a></div>\n";
    }
}
print "\n</div>\n";
# kludge to prevent the 'lolling tongue problem'
if ( $foreachcount < 5 ) {
    pad($padpad);
}
endpage($scriptname);
}


# ---------------------------------------------------------------------
# kludge to prevent the 'lolling tongue problem'
function pad($pbot) {
    print "<div style=\"font-size: .01em; padding-bottom: ${pbot}px;\">";
    print "&nbsp;</a></div>\n";
}




############################## mkpost ############################
# This is a simple shell script that you might find handy.
# If you dont know what a shell script is, ignore this section.
#
# --------- cut --------------------------------------------------
##!/bin/sh
## mkpost - simple shell script to make new (almost certainly) unique
##          Agolbloga posts.
##
## note: if you are using agoladmin and mkpost, you will need to 
## use sudo to run this script since permissions on the directory
## will not allow your user account to write and because the file
## must be chowned upon save.
##
## set your preferences here
#editor="/usr/bin/vi"
#pager="/usr/bin/less"
#owner="www" # os x apache
##owner="nobody" # *nix apache
##
##now=`date '+%g%m%d.%H%M%S'`
#now=`date '+%s'`
#$editor $now
#$pager $now
#echo 
#echo "1. Save $now and Publish"
#echo "2. Save $now only"
#echo -n "Select: "
#read RESP
#case "$RESP" 
#   in
#   1) mv -i $now $now.txt; chmod 644 $now.txt; chown $owner $now.txt;;
#   2) echo "$now not published. You can publish it by renaming it '$now.txt'";;
#esac
# --------- cut --------------------------------------------------
############################# mkpost ############################

# end of Agolbloga 

?>

