#!/usr/pkg/bin/php
<?php
// A simple guestbook for Motsgnir gopher server (php)
// [email protected], 4/20/16

//$thisRoot = str_replace("/sdf/ftp/pub","",__DIR__);
//$siteUrl = $_SERVER['SERVER_NAME'];
//$SERVER_PORT = "70";

$serverUrl = $_SERVER['SERVER_NAME'];
//$serverUrl = "gopher.jozhaus.com";
$guestBookFile = "/sdf/ftp/pub/users/tfurrows/cgi-bin/guestBook.dat";

$terminate = "\tx\tx\t0\r\n";
$ascLine = str_repeat("-",50);


echo "iJozhaus Guest Book".$terminate;
echo "7Sign the guest book\t/users/tfurrows/cgi-bin/guestBook.php\t$serverUrl\t70".$terminate;

echo "i".$terminate;
//echo "i".$ascLine.$terminate;
//echo "i".$terminate;

// Read all of the current guestbook entries
$handle = fopen($guestBookFile, "r");
if($handle) {

       while (($line = fgets($handle)) !== false) {
               $lineCount+=1;
               $bookLine[] = $line;
       }

       // No one has signed yet
       if(!isset($bookLine)) {
               echo "iNo one has signed the guest book yet. Be the first!".$terminate;
       }

       fclose($handle);
} else {
       // error opening the file.
       echo "iThere was an error, the guest book file does not exist.".$terminate;
}



// Process guest book signatures
if(($inputString = getenv("QUERY_STRING"))>"") {
       // Build the signature / message to save in the file
       $remoteIp = getenv("REMOTE_ADDR");

       $message[] = $ascLine;
       $message[] = $inputString;
       //$message[] = "   From: ".$remoteIp.", ".date("D M j G:i:s T Y");
       $message[] = "   ".date("D M j G:i:s T Y");
       $message[] = $ascLine;

       // Write to the guestbook, prepend
       file_put_contents($guestBookFile,implode("\n",$message));

       // If there were previous entries, we'll add them after this new one
       if(isset($bookLine)) {
               file_put_contents($guestBookFile,implode($bookLine),FILE_APPEND | LOCK_EX);
       }
}

// Display guest book contents

if(isset($message)) {
       foreach($message as $bookLineText) {
               echo "i".$bookLineText.$terminate;
       }
}

echo "i".$terminate;

$count=0;
if(isset($bookLine)) {
       foreach($bookLine as $bookLineText) {
               $count++;
               // 5 lines in the text file per entry, use modulus to insert a gopher menu item ever n items (x5)
               // so scrolling works for long guestbooks
               if($count%15==0) {
                       echo "1Scroll Down\t/guestBook.php\t$serverUrl\t70".$terminate;
               }
               echo "i".rtrim($bookLineText).$terminate;
       }
}

// Link to the source
//echo "i".$ascLine.$terminate;
echo "0View the PHP source for the guestbook\t/guestBook.txt\tgopher.jozhaus.com\t70".$terminate;

include("/var/gopher/footer.php");
?>