<?php
//start session so we can assign session vars later
//(must start before any output)
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>:: Guestbook By PrintedExistence[dot]com ::</title>
<link rel="stylesheet" href="guestbookstyles.css" type="text/css" />
</head>

<body>

<h2>Welcome to My Guestbook!</h2>

<table class="maintable"><tr><td>

<?php
/**********************************************************
 Flat File Guestbook Script Version 2 (November 2007)
 By ElectricStorm, PrintedExistence[dot]com
 this script is free, opensource and provided as is.
***********************************************************/


$msgs_per_page = 20; //the number of messages to display per page
$file = "guestbookmsgs.txt"; //the path to an empty text file where messages will be stored
$date = date("Y-m-d H:i:s", time()); //sets the display format of the date


// first, try to get txt file with messages on:
if (!is_file($file)) { echo("Couldn't find the messages file!"); }
else {


    //IF USER HAS JUST POSTED A NEW MESSAGE:
    if ($_POST['submit'] == "Add Message") {

        //check the verification code matches the one we sent in the image (see iamhuman.php):
        if (md5($_POST['verify']) != $_SESSION['iamhuman']) {
            echo("<div class=\"error\">Either you are a spambot, or you entered the wrong verification code!</div>");
        } else {

            //define unwanted chars, and what they should be replaced with:
            $invalid = array('/|/','/</','/>/','/\\n/','/\\r/','/\\t/');
            $replacewith = array('','','','<br \/>','','');
            //strip unwanted characters from posted vars:
            $from = preg_replace($invalid, $replacewith, stripslashes($_POST['from']));
            $message = preg_replace($invalid, $replacewith, stripslashes($_POST['message']));

            //if the posted message isn't empty...
            if (!empty($message)) {
                echo("<div class=\"error\">Oops! You didn't write a message!</div>");
            } else {

                //if from field isn't filled use Unknown:
                if (empty($from)) { $from = "Unknown"; }

                $read = file($file); //fetch contents of messages file
                $open = fopen($file, "a"); //open the file for adding to (a = append)
                flock($open, LOCK_EX); //lock so that noone else can edit this file while we are
                fwrite($open, $from."|".$date."|".$message."\n"); //write the new message in
                flock($open, LOCK_UN); //release lock
                fclose($open);
            }

        } //end else (image matches ok)
    } //end if (new message posted)


    //THIS PART DISPLAYS EXISTING MESSAGES:
    $read = file($file); //read contents of messages file into array
    $read = array_reverse($read); //reverse order so that most recent message is first
    $linecount = count($read);

    //see if there is a page number in the url:
    if (!ctype_digit($_GET['page'])) { $thispage = 1; } //if not, we're on page 1
    else { $thispage = $_GET['page']; } //if so, we're on the page number given in the url

    //define page numbers to show above / below the messages:
    $pagenumbers = "<div style=\"text-align: right; margin: 5px;\">";
    for ($i = 1; $i <= ceil($linecount / $msgs_per_page); $i++) { //(ceil rounds up)
        if ($i == $thispage) { $pagenumbers .= "[".$i."] "; } //don't make it clickable if it's the page we're currently on
        else { $pagenumbers .= "<a href=\"".$_SERVER['PHP_SELF']."&#63;page=".$i."\" title=\"page ".$i."\">[".$i."]</a> "; }
    }
    $pagenumbers .= "</div>";

    //if more than 1 page display page number above the messages:
    if ($linecount > $msgs_per_page) { echo($pagenumbers); }

    //get first message on this page:
    $firstmsg = ($thispage -1) * $msgs_per_page;
    //get last message on this page:
    $lastmsg = $firstmsg + ($msgs_per_page -1);

    //loop through however many messages we want to display:
    for ($line = $firstmsg; $line <= $lastmsg; $line++) { //for each line of the file:
        if (!empty($read[$line])) { //if there is a message:
            $parts = explode("|", $read[$line]); //split the line into sections (defined by | marks in the text file)
            echo("<table class=\"subheading\"><tr><td style=\"text-align: left;\"> From: ".$parts[0]." </td>
            <td width=\"200px\" style=\"text-align: right;\">on ".$parts[1]."</td></tr></table>".$parts[2]."<br /><br />");
        }
    }

    //if more than 1 page display page number below the messages:
    if ($linecount > $msgs_per_page) { echo($pagenumbers); }
    ?>

    </td><td width="150px">

    <br />
    <form action="" method="post">
    From: <input type="text" name="from" size="20" maxlength="100" />
    <br />Message:
    <br /><textarea rows="5" cols="20" name="message"></textarea>
    <br /><img src="iamhuman.php" alt="image verification" style="border: 1px solid #999999;" />
    <br />Enter the above code: <input type="text" size="15" maxlength="10" name="verify" />
    <br /><input type="submit" name="submit" value="Add Message" />
    </form>

<?php
} //end else (got file with messages on ok)
?>

</td></tr></table>

</body>
</html>