<?php


//////////////////////////////////////////////////////////////////////
// 
// QUICK INSTALLATION INSTRUCTIONS (save this file as index.php)
// 
// 1. Create a directory;
// 2. Make sure it's read-write-execute'able by everyone;
// 3. Put index.php in there (make sure it's read'able by everyone);
// 4. Make sure you have php (with gd support) on your system and get
//    the three images (transparent-pixel.gif, post.gif,
//    go-black-tiny-button.gif) from http://www.sethi.org/tools/releases/
// 5. Everything should work immediately, as is!
//    But you still might want to set these options/customizations (by section order):
//    1. "INITIAL OPTIONS SETTINGS" is all that's *REQUIRED* to be reviewed and set
//    2. "File Locations" will be automatically set but customize as you please;
//    3. "Authentication Functionality" can be customized
//    4. "GuestBook Functionality" can be customized
//    5. "GuestBook Appearance" is where you can customize the displayed text
// 
//////////////////////////////////////////////////////////////////////


//////////////////////////////////////////////////////////////////////
// 
//      Program: Sethi Family Guestbook
// 
//      Version: 3.1.8
//               Sample at http://www.sethi.org/guestbook/
// 
//      Output:  Guestbook automagickally creates:
//               - guestdata.txt (contains guest data)
//               - guestlog.html (entries' log file)
//               - tmpguestdata.txt (contains guest data)
// 
//  Description: 
//               
//               The Sethi Family Guestbook is a multi-format guestbook script written
//               as a single PHP file that requires no installation. It features page
//               spanning, (optional) private comments, user-selection of number of
//               entries per page to display, multiple guestbook formats (elegant,
//               simple, or standard), and background color. No database is required.
//               It supports image verification using random text as part of a CAPTCHA system. 
//               It also uses other techniques to foil spam robots. It supports multiple 
//               formats, mangled email display, and a fully customizable interface.
//               
//               This program is a single file which can be placed in any directory to
//               instantly put up a guestbook for your site.  It generates a couple of
//               files automatically so you'll have to ensure that directory is
//               writeable by the web server.  It supports multiple formats, mangled
//               email display, and a fully customizable interface.  The Sethi Family
//               Guestbook now supports image verification using random text as part of
//               a CAPTCHA system.  It incorporates elements designed to foil bots by
//               confusing OCR software and also uses strong PHP session security in
//               order to disallow them getting around it (e.g., preventing brute force
//               attacks, slip-through attempts, etc.).  Also, disallows blank
//               sessionIDs, which is a great anti-spam technique for guestbooks,
//               etc. to use against spambots that exploit PHP's vulnerability, a la
//               sending fake requests with blank sessionIDs.  It also supports
//               multiple formats that the user can pick between on the fly, mangled
//               email display, and a fully customizable interface.
//               
//               Finally, it is completely free (as long as you credit us... see below! :).
// 
//      License:
//               GPL & Postcard-Ware!  If you like this program and
//               use it, drop me a postcard or an email or just sign
//               our guestbook and tell me how great I am. :)  And
//               hey, if you *really* like it, don't worry about
//               designing that shrine dedicated to my greatness... a
//               simple link back to our homepage should suffice.  
// 
//               ****************************************************
//               Also, if you do use this script, please forward your
//               guestbook and homepage URLs to me at rickys@sethi.org
//               as I'll be compiling a page of users of the script
//               from around the world (should help pump some traffic
//               your way, too). 
//               ****************************************************
// 
//      Credits:
//               Original idea very loosely based on Matt's Perl
//               Guestbook (http://www.worldwidemart.com/scripts/) 
// 
//      Author:
//               Ricky J. Sethi (rickys@sethi.org)
//               http://www.sethi.org/
// 
//      Changes:
//               This is the last version that will be packaged in 
//               a single file; subsequent releases will be modular
//               (i.e., better written! :o) and allow for mysql support.
// 
//               
//               * Added the Image Authentication Verification (CAPTCHA)
//               * Added PHP Session support
//               * Blocked against brute force session attacks (e.g., using vhosts)
//               * Blocked against spambot session hijacking/slipthrough
//               * Added better customizations and automatic guessing
//               
//               * Made sure all href's were absolute (added $cgiurl
//                 to href's in PrintNavControl and PrintTopNav)
//                 thanks to Don Graver (http://www.dgraver.com)
//               * Mangled displayed email
//               * Allow customization of addform (parcel out in fxn) 
//               * Ditto the (whole) header
//               * Allow for single format only option ($multi_format)
//               * Added mail functionality
//               * List newest entries first (or last) option added
//               * Shifted ADD form (& intro) to end of first page
//               * Change Errors to return the same page with
//                 different $bcol 
// 
//               * Fixed allow_html error and default
// 
//               * Added Google Adsense
// 
//      TODO:
//               * Add icons
//               * Add word filtering (for curse words, etc.)
//               * Put IP field in guestbook formats
//               * Add entry editing interface facility
//               * Put stuff out into separate files (e.g., fxns, html
//                 templates, etc.) & template directory
//               * More security checks on passed data (esp. for mail
//                 options) 
//               * Add MySQL backend (rewrite for either flat-file OR
//                 db data storage sink) 
//               * Return-Path: header doesn't always work... why?
// 
/////
// For the coders:  Please note, this is *really* legacy code (I wrote
// some of it almost 10 years ago!) so some code (the newer code) is
// much better written and sturdier than other code (the older junk).
// I intend to completely rewrite this thing One Fine Day, (copyright
// 2005 :); all OOP stuff and good $GLOBALS, $_GET, etc. usage is new.
// 
//               * 2006-05-05: $comments changed to $comment in
//                 PrintAddForm since register_globals is now off by
//                 default 
// 
//               * 2006-05-11: Apparently, had missed a few $comments
//                 and they caused a bit of havoc in private
//                 comments... fixed by changing to $orig_comments
//                 (and secured more by mailing out only the parsed
//                 $orig_comments) -- minor Bugfix
// 
//               * 2006-05-17: Added $guestlogname and $guestlogurl -- minor Bugfix
// 
//               * 2006-05-25: Added $navbarpath and $jsfilepath -- minor Bugfix
// 
//               * 2006-06-13: Fixed piggy-back/session hijacking hacking attempt hole
// 
//               * 2006-07-01: Fixed guestlog/tmpguestlog mixup, guestlog
//                 non-creation snafu, and false reporting of mis-matched
//                 authentication code on a submission with missing data
// 
//               * 2006-08-01: Fixed basehref bug for IE
// 
//               * 2007-04-11: Added rel="nofollow" attribute to all 
//                 signers' links to discourage spammers/spambots
//                 @REFERENCE: http://blog.searchenginewatch.com/blog/050118-204728
// 
//               * 2007-06-11: Fixed missing $guestbookurl in "sign in
//                 below" and ADDreferences.  Also made bad_bot logging
//                 optional (off by default).
// 
//               * 2007-06-13: Made it compatible with PHP5, including
//                 using superglobals, doing isset() checks, checking
//                 for undefined variables/index, default_timezone, etc.
// 
//               * 2007-06-17: Simplified installation customization.
// 
//               * 2008-02-07: Fixed allow_html bug-fix and default setting.
/////
// 
//////////////////////////////////////////////////////////////////////





//////////////////////////////////////////////////////////////////////
//
// Customizations -- make changes below
// (this whole section HAS to be before ANY HTML tags)
// 
//////////////////////////////////////////////////////////////////////



//////////////////////////////////////////////////////////////////////
// INITIAL OPTIONS SETTINGS:
// 
//

// -------------------------------------------------------------------
// GuestBook Functionality (recommended)
// -------------------------------------------------------------------

// Should our guestbook be moderated by a live human? (usually no)
$moderated     0;            // 1 = Yes; 0 = No

// Set additional options
// $uselog is if we'd like to log stuff to guestlog.html (usually yes)
$uselog         1;            // 1 = Yes; 0 = No
// $doBadBotLogging is if we'd like to log some debugging/bot-tracking info to /tmp/bad_bot.log (usually no)
$doBadBotLogging 1;            // 1 = Yes; 0 = No
// Whether to use Location redirection header after a successful entry (usually yes)
$redirection     1;        // 1 = Yes; 0 = No  
// Determines order of entries displayed (newest first or oldest first)
$entry_order     1;        // 1 = Newest entries listed first;
                // 0 = Newest entries listed last.

// Do we allow HTML tags (meta tags are automatically filtered irrespective)
$allow_html     0;        // 1 = Yes; 0 = No
// Should we display the signers' email address in the guestbook?
$linkmail     1;        // 1 = Yes; 0 = No
// If they press enter a lot within their comment, should we add those empty lines to the final comment?
$line_breaks     0;        // 1 = Yes; 0 = No
// Should we allow them to switch formats (e.g., elegant, simple, standard, etc.)?
$multi_format     1;        // 1 = Yes; 0 = No

// $mail is to send a mail to us; $remote_mail is to send email to signer
// If you answer 1 to $mail or $remote_mail you will need to make
// sure that the sendmail path option is set in your php.ini
$mail         1;        // 1 = Yes; 0 = No
$remote_mail     0;        // 1 = Yes; 0 = No

// Default password for private comments:
$defaultpassword "3";


// -------------------------------------------------------------------
// Some additional settings:
// -------------------------------------------------------------------

// Will you have a navigation bar in the footer (this is optional)?
// If so, please also set $myssipath, $myssi, and $navbarpath below.
$includeFooterNavbar 1;           // 1 = Yes; 0 = No

// Will you include the js-common.js (this is optional)?
// If so, please also set $myssipath, $myssi, $jsfilepath, and $jsfile below.
$includeJavascript   1;           // 1 = Yes; 0 = No


// -------------------------------------------------------------------
// GuestBook Appearance (optional)
// -------------------------------------------------------------------

// Set our images (get em from http://www.sethi.org/tools/releases/):
$transpgif       "/images/misc-gifs/transparent-pixel.gif";
$postgif         "/images/icons/post.gif";
$goblack         "/images/buttons/go-black-tiny-button.gif";

// MetaTags
$description     "Welcome to The Sethi Family's Guestbook";
$keywords        "Sethi, sethi, Sethi Family, sethi family, family, guest, guests, guestbook";

// Header info stuff
$titleTag        "Sethi Family Guestbook";
$titleTag2       "Guestbook for The Sethi Family";
$homepageText    "The Sethi Family HomePage";

// Title text/body:
$titleText       "";   // Defaults to "Thank you for visiting us..."
$titleBody       "";   // Defaults to "Thanks for dropping by our homepage... now here's your chance to tell us..."


// Referrer Source Options:
$referrer_opt    = <<<REFOPTIONS
          <option value="by following a pagan ritual"> by following a pagan ritual
          <option value="by accident (i.e., in a drunken stupor)"> by accident (i.e., in a drunken stupor)
          <option value="by following a recommendation"> by following a recommendation
          <option value="by following a link from another page"> by following a link from another page
          <option value="by looking for us on Yahoo"> by looking for us on Yahoo
          <option value="by looking for us on Infoseek"> by looking for us on Infoseek
          <option value="by looking for us on Excite"> by looking for us on Excite
          <option value="by looking for us on Lycos"> by looking for us on Lycos
          <option value="by looking for us on AltaVista"> by looking for us on AltaVista
          <option value="by looking for us on WebCrawler"> by looking for us on WebCrawler
          <option value="by looking for us on some News Group"> by looking for us on some News Group
          <option value="by following YOUR recommendation, ya schmuck!"> by following YOUR recommendation, ya schmuck!
REFOPTIONS
;


// Set Javascript Variables (escape all ')
// This is the text for the password pop-ups
$promptString1   "And the password is..."
$promptString2   "Hmmm... how about... Abracadabra?"
$alertString     "Nope!  Who do you think you are?  Kevin Mitnick??  You know, maybe you should think about getting outta the hacking biz... hey, how about a job as a court reporter?  It says here that you can make up to $30k a year!  And you wouldn\\'t have to worry about hacking all those silly passwords, either..."
//////////////////////////////////////////////////////////////////////






//////////////////////////////////////////////////////////////////////
// File Locations (required)
//

// Some necessary customizatons:
// Do NOT change these three lines
$webroot                preg_replace('%/[^/]*$%'''$_SERVER['SCRIPT_NAME']);     // result: /guestbook
$fileroot               preg_replace('%/[^/]*$%'''$_SERVER['SCRIPT_FILENAME']); // result: /path/to/htmlroot/guestbook
$htmlroot               preg_replace("%$webroot%"''$fileroot);                  // result: /path/to/htmlroot

// DO change these four lines if you'd like to customize it
// Ensure write-permissions for these automatically generated files
$guestbookdata            "$fileroot/guestdata.txt";
$guestlogname            "guestlog.html";
$guestlog            "$fileroot/$guestlogname";
$tmpguestbookdata    "$fileroot/tmpguestdata.txt";
$tmpguestlog            "$fileroot/tmpguestlog.html";

// Our full URLs
// Do NOT change this line
$server         $_SERVER['SERVER_NAME'];                        // result: www.yoursite.com

// DO change these two lines, if you like
// Don't forget the trailing slash if it's *not* a file (i.e., dir) 
$homeurl    "http://$server/";                              // e.g., http://yoursite.com/
$guestbookurl    "http://$server/" ltrim($webroot,"/") ."/";   // e.g., http://yoursite.com/guestbook/
$guestlogurl    "http://$server/" ltrim($webroot,"/") ."/$guestlogname";   // e.g., http://yoursite.com/guestbook/guestlog.html

$basehref       $homeurl;                                       // E.g., http://www.sethi.org/guestbook/


// DO change these three lines, if you like
// Some included files
// Ensure valid (relative) path (leave blank if none)
$myssipath    "$htmlroot/ssi";                           // Get our SSI actual root dir path (optional)
$myssi          "/ssi";                                    // Get our SSI web dir (optional)
$navbarpath    "$myssipath/navbar.html";                  // Navigational Bar path (optional)
$navbar     "$myssi/navbar.html";                      // Navigational Bar (optional -- LEGACY -- UNNEEDED)
$jsfilepath    "$myssipath/js-common.js";                 // Extra Javascript Stuff path (optional)
$jsfile     "$myssi/js-common.js";                     // Extra Javascript Stuff (optional)

// Do NOT change these four lines unless you really know what you're doing
// Perl (legacy) stuff (no need to mess with these, really)
// Change $cgiurl if your script is different from your guestbook URL 
$cgiurl         $guestbookurl;                      // e.g., http://yoursite.com/guestbook/gb.php
$postGuestbook  $cgiurl;
$datafile    $guestbookdata;
$file_splitter  "--------------------------------------------------";
$downloadLink   "http://www.sethi.org/tools/releases/guestbook-index.phps";
//////////////////////////////////////////////////////////////////////




//////////////////////////////////////////////////////////////////////
// Authentication Functionality (necessary)
//

// DO change these three lines (to make your site more secure)
$session_label 'lkjs2389ilnm23l8ms';  // Session Code Label (CHANGE THESE!)
$post_label    'kja;sdjlij289j2lk2';  // Post Code Label (CHANGE THESE!)
$max_num_label 'max_attempts';        // Maximum Attempts Label (change for yourself!)

// DO change these three lines (if you know what you're doing)
$logfile      "/tmp/bad_bot.log";     // Bad_Bot log file (brute force)
$numChars     5;                      // Size of String: default 5 (in case a spambot tries to set size=0 parameter)
$max_attempts 5;                      // Max number of allowed attempts (brute force)
                                        // (slip-through attacks are more deadly so leave this relatively big)

//////////////////////////////////////////////////////////////////////





//////////////////////////////////////////////////////////////////////
// GuestBook Functionality (recommended)
//

// Our guess to what our email address ($recipient) should be --
// Please change if the guess ain't no good! :)
// Get just Top Level Domain and construct email: guestbook@top_level_domain.com
$domain          explode('.',$server);
$tld             $domain[count($domain)-2] ."."$domain[count($domain)-1];
$recipient     'guestbook@' $tld;


// Legacy: not used
$separator     1;        // 1 = <hr>; 0 = <p>
//////////////////////////////////////////////////////////////////////




//////////////////////////////////////////////////////////////////////
// GuestBook Appearance (optional)
//

// Title text/body:
if ( !isset($titleText) || empty($titleText) )
   
$titleText       "Thank you for visiting us...  please <a href=\"$guestbookurl#add\"><font color=\"red\">sign in below</font></a>";

if ( !isset(
$titleBody) || empty($titleBody) )
   
$titleBody       = <<<TITLEBODY
Thanks for dropping by our homepage... now here's your chance to
tell us all your intimate hopes and dreams for the whole world (wide
web) to see.  Who knows?  Maybe a newly-christened Internet
Millionaire (&#169 Copyright 1999, The Sethi Family) will
spot your entry and fulfill all your deepest desires.  Hey, it's
better than a chain letter at least!  So crank up those rusty
gears and <b><a href="
$guestbookurl#add">ADD</a></b> your unique voice to our
archives!

<P>

<!--
<font size=-2><b>Legalese</b>: We promise that we will never release
any personal information here to any commercial enterprise (sucker!).
We further promise that the whole Sethi Family will spend countless
hours gathered around a fireplace laughing at your pathetic existence
and making fun of all your intimate hopes and dreams.  Thank you for
giving us something to do during those long months of summer
reruns... Further, by sheer virtue of just clicking here, you
acknowledge that Hanson and The BackStreet Boys are two definite signs
of the coming Apocalypse and hereby acquiesce to give an annual
donation of not less than $1,000,000 for the next 273 years to the
Ricky J. Sethi lazy-ass trust fund...</font>

<P>
-->
TITLEBODY
;


// Set addForm bgcolor:
$bcol            "#CCCCCC";



// Set the default background colour:
if (! isset( $_GET['bg'] ) ) {
  
$bg="E0E0E0";
} else {
  
$bg=$_GET['bg'];
}

// Make bgcolour array:
$bgcolours       = array (
  
"E0E0E0",
  
"AntiqueWhite",
  
"DarkTurquoise",
  
"LightGrey",
  
"MediumAquamarine",
  
"SeaShell",
  
"Silver"
);

// Set default format:
if (! isset( $_GET['f'] ) ) {
  
$f="Elegant";
} else {
  
$f=$_GET['f'];
}

// Make format array:
$formats = array (
  
"Elegant",
  
"Simple",
  
"Standard"
);

// $number is number of entries per page
if (! isset( $_GET['number'] ) ) {
  
$number 50;
} else {
  
$number=$_GET['number'];
}
//////////////////////////////////////////////////////////////////////


        

//////////////////////////////////////////////////////////////////////
// GuestBook Appearance Template (editing not recommended)
// (stuff that will go out into template files later)
//


///// Title & Header
function PrintTitleHeader() {
   
// Declare my globals (so it doesn't just create a new, local var)
   
global $titleTag$titleText$transpgif;

   print <<<TITLEHEADER
<table border=0 cellPadding=0 cellSpacing=0 width=100%>
  <tbody>
  <tr>
    <td bgColor=black vAlign=top>
    <table border=0 cellPadding=0 cellSpacing=0 width=100%>
      <tr>
    <td bgColor=black colSpan=8 vAlign=center>
    <font color=#ffcc00 face=Arial,helvetica
    size=6><B>&nbsp;
$titleTag</font></b>
    <br><br>
    </td>
    <td align=right bgColor=black colSpan=2 height=45
    vAlign=center>
    </td>
      </tr>
      </table>
    </td>
  </tr>
  <!--<tr><td bgColor=skyblue align=right></td><img src="
$transpgif" height=1></tr>-->
  <tr>
    <td bgColor=black align=right>&nbsp;&nbsp;&nbsp;
    <font face=times size=4 color=red><i><b>
$titleText&nbsp;</b></i>
    </font><!--We would love it if you would <i>add</i> to this guestbook-->
    </td>
  </tr>
</table>
TITLEHEADER
;
}


///// Top navigational table
function PrintTopNav() {
   
// Declare my globals (so it doesn't just create a new, local var)
   
global $number$no_entries$bg$f$cgiurl;

   print <<<TOPNAV
<table cellpadding=3 width=100%>
<tr>
   <td align=left>
   <br>
   <a href="
$cgiurl#entries">
   <font face="times" size=4 color=blue><b>
   First 
$number entries
   </b></font>
   </a>
   </td>

   <td align=right>
   <a href="
$cgiurl?number=$no_entries&bg=$bg&f=$f">
   <font face="times" size=4 color=blue><b>
   All 
$no_entries entries
   </b></font>
   </a>
   </td>
</tr>
</table>
TOPNAV
;
}


///// The Add Form
function PrintAddForm() {
   
// Declare my globals (so it doesn't just create a new, local var)
   
global $postGuestbook$bcol$transpgif$pwidth$referrer_opt;
   global 
$name$email$url$city$state$country$referrer$orig_comments$comment$private$password$ip;
   global 
$vImage$code_submitted$myName;

   if (!
$url) {$url "http://";}
   if (!
$country) {$country "USA";}


   print <<<ADDFORM1
<form method="post" action="$postGuestbook">
<CENTER>


<!-- borderTableOnly -->
<table border="1" cellpadding="0" cellspacing="0" 
bordercolor="mediumaquamarine" bgcolor="gray" bordercolorlight="black">
<TR><TD>



<!-- actualFormContent -->
<table width="550" border="0" bgcolor="
$bcol" cellspacing="0" cellpadding="2">
<tr>
   <td height=25 colspan=2 bgcolor="
$bcol" align=center valign=top>
       <small>Please enter at least your name along
       with the correct authentication code and your comment(s)... Thanks!</small></td></tr>


<tr>
   <td bgcolor="
$bcol"><font size=-1 face=Verdana><B>Your Name:</B></td>
   <td bgcolor="
$bcol"><input name=realname type=text size=40 maxlength=100 value="$name"></td></tr>

<tr>
   <td bgcolor="
$bcol"><font size=-1 face=Verdana>E-mail:</td>
   <td bgcolor="
$bcol"><input name=username type=text size=40 maxlength=100 value="$email"></td></tr>

<tr>
   <td bgcolor="
$bcol"><font size=-1 face=Verdana>Homepage URL:</td>
   <td bgcolor="
$bcol"><input name=url type=text size=40 maxlength=100 value="$url"></td></tr>

<tr>
   <td bgcolor="
$bcol" colspan=2 valign=bottom><font size=-1 face=Verdana>Geographical Info:</td></tr>
<tr>
   <td bgcolor="
$bcol"><font size=-1 face=Verdana><small>&nbsp;&nbsp;&nbsp;City, State, Country</small></td>
   <td bgcolor="
$bcol"><input type=text name=city size=15 value="$city">, <input type=text name=state size=2 value="$state">, <input type=text name=country size=15 maxlength=100 value="$country"></td></tr>

<tr>
   <td bgcolor="
$bcol" valign=bottom height=25><font size=-1 face=Verdana><small>How did you stumble <br>into our Virtual Home?</small></td>
   <td bgcolor="
$bcol">
       <select name="referrername">
     
$referrer_opt
        </select></td></tr>
<tr><td bgcolor="
$bcol" colspan=2><img src="$transpgif" height=5></td></tr>

<tr>
   <td bgcolor="
$bcol" valign=top><font size=-1 face=Verdana><B>Comments:</B></td>
   <td bgcolor="
$bcol"><textarea name=comments rows="10" cols="45">$orig_comments</textarea></td></tr>
<tr><td bgcolor="
$bcol" colspan=2><img src="$transpgif" height=5></td></tr>
</table>


<table width="550" border="0" bgcolor="
$bcol" cellspacing="0">
<tr>
   <td bgcolor="
$bcol" colspan="5">
   <table width="
$pwidth" cellpadding="3">
     <tr><td valign=bottom colspan=3><input type=checkbox name="private"
ADDFORM1
;

   
// Check private box?
   
if ($private) { print " checked"; }

   print <<<ADDFORM2
       ><font face=\"arial\"><i>&nbsp;Make it private?</i></font></td></tr>
     <tr>
       <td><img src="
$transpgif" width=23></td>
       <td><font size=-1 face=verdana>If private, please specify password (case sensitive)<BR>
       <font face=arial size=-2>Sorry, can't use HTML in a private comment.  Also, if no password is specified, default password will be assigned.</font></font></td>
     <td valign=top align=right><input type=text name=password size=15 value="
$password"></td>
   </tr></table>
<p>
</td></tr>
</table>


<!-- IMAGE AUTHENTICATION START -->
<table width="550" border="0" bgcolor="
$bcol" cellspacing="0">
<tr>
   <td bgcolor="
$bcol" colspan="5">
   <br><img src="
$myName?$vImage->image_size_label=5&amp;$vImage->image_display_label=1"></div><br>
   <input type="hidden" name="code_submitted" value="1">
   <font size="2" face="Verdana, Arial, Helvetica, sans-serif"><b>Please enter the code you see above: </b></font>
ADDFORM2
;
  
  
  
$vImage->showCodBox(1);
  

   print <<<ADDFORM3
   <br /><font face="arial" size="-2">(Or hit REFRESH if it's broken)</font>
   </td>
</tr>
</table>
<!-- IMAGE AUTHENTICATION END -->


<!-- /actualFormContent -->


</table>
<!-- /borderTableOnly -->

<BR>
      <CENTER>
      <input type=submit> * <input type=reset>
<BR>
      </CENTER>

</CENTER>

    </form>
ADDFORM3
;
}

//////////////////////////////////////////////////////////////////////








//////////////////////////////////////////////////////////////////////
//
// No need to make any changes below here
// 
//////////////////////////////////////////////////////////////////////


/////////////// Set Some Variables ///////////////
// 2007-06-13: For PHP5, set the timezone:
date_default_timezone_set("America/Los_Angeles");

// Figure out the date (e.g., Tuesday, June 1, 1999 at 7:11 PM and 6/4/1999 17:42)
$dayOfWeek    date("l");
$monthOfYear  date("F");
$thisMonth    date("n");
$thisDay      date("j");
$yearNumber   date("Y");
$mytime          date("g:i A");
$thisHour     date("G");
$thisMinute   date("i");

$myLongDate   "$dayOfWeek$monthOfYear $thisDay$yearNumber at $mytime";
$myShortDate  "$thisMonth/$thisDay/$yearNumber $thisHour:$thisMinute";

// Get the Date for Entry (legacy code)
$date          $myLongDate;
$shortdate    $myShortDate;

$myName       $_SERVER['PHP_SELF'];                 // result: /guestbook/index.php



//////////////////////////////////////////////////////////////////////
// 
//      Library: authenticate_image.phtml
//      Version: 0.3.8
//               Used in http://www.sethi.org/guestbook/
//  Implemented: Implemented in same file (at the end)
// 
//  Description: This class generates an image with random text that
//               can be used as part of a CAPTCHA (see below) system and used as image
//               verification for forms of any sort (this was developed in the context
//               of The Sethi Family GuestBook.  It incorporates elements designed to
//               foil bots by confusing OCR software and also uses strong PHP session
//               security in order to disallow them getting around it (e.g., preventing
//               brute force attacks, slip-through attempts, etc.).
//               Also, disallows blank sessionIDs as a great anti-spam technique for guestbooks,
//               etc. to use against spambots that use PHP's vulnerability, a la
//               sending fake (/guestbook/?PHPSESSID=e295d8b99fb4a8b38bd496373391b803&number=724)
//               requests with blank sessionIDs.
// 
//      License:
//               GPL & Postcard-Ware!  If you like this program and
//               use it, drop me a postcard or an email or just sign
//               our guestbook and tell me how great I am. :)  And
//               hey, if you *really* like it, don't worry about
//               designing that shrine dedicated to my greatness... a
//               simple link back to our homepage should suffice.  
// 
//               ****************************************************
//               Also, if you do use this script, please forward your
//               guestbook and homepage URLs to me at rickys@sethi.org
//               as I'll be compiling a page of users of the script
//               from around the world (should help pump some traffic
//               your way, too). 
//               ****************************************************
// 
//      Credits:
//               Original idea based on Rafael Machado Dohms' vImage in Portugese
//               http://planeta.terra.com.br/informatica/d2000/vImage/vImage_withexamples.zip
// 
//      Author:
//               Ricky J. Sethi (rickys@sethi.org)
//               http://www.sethi.org/
// 
//   References: Some links and references for CAPTCHA (image verification):
//               * CAPTCHA decoder: http://sam.zoy.org/pwntcha/
//               * Basic CAPTCHA: http://captchas.net/sample/php/
//               * Basic image authentication:  http://www.php-mysql-tutorial.com/user-authentication/image-verification.php
//               * Basic image authentication:  http://www.weberdev.com/get_example-4067.html
//               * Also see veriword and freecap and PHP XSS attacks (http://www.hardened-php.net/advisory_012006.112.html)
// 
//      Changes:
//               This version now implements the following:
//               * 2006-05-05: 
//                 * Changed session_labels, etc.
//                 * Added $sessionCode, $postCode initialization
//                 * Initialized class vars in constructor using GLOBALS
//                 * Used $_GET instead of $_SERVER to do check
//                 * Increased num of max_attempts and numChars
//               
//               * 2006-05-03: Changed implementation to be in same file (at the end)
//               
//               * Logging of successful, bad_bot (brut force), and slip-through attempts
//               * Code to actually prevent slipthrough attacks (most effective anti-spam technique)
//               * Stops brute force attacks of re-using session across attempts or vhosts
// 
//      TODO:
//               * 
// 
//////////////////////////////////////////////////////////////////////





//////////////////////////////////////////////////////////////////////
//
// Changes:
//
// 2005-08-07: Last time of update/change before better time accounting
// Made my own changes to this... messed with class to make it less stringent
// Added ?php everywhere
// Need img.phtml?size=5 to create the image
// Use the image in form.phtml and verify in verify.phtml
// Combine form.phtml and verify.phtml into one file: combined.phtml; added $code_submitted
//
// 2006-04-30: Added brute force attack countering based on
// freecap.php (basically, if they try to use the session's stored
// code to keep making spam entries, we instead reset the session
// after $max_attempts and then also log the attempt in the
// /tmp/bad_bot.log file
//
// 2006-05-01: Added logging successful, bad_bot, and slip-through
// (most vicious/effective) attempts.  Also added code to actually
// catch and prevent slipthrough attacks (BEST anti-spam technique).
// 
//////////////////////////////////////////////////////////////////////




class vImage {

  
//////////////////////////////////////////////////////////////////////
  //
  // Customizations -- make changes below (also set via globals, above)
  // 
  //////////////////////////////////////////////////////////////////////

  
var $h               20;                     // Height of Image: default 20;
  
var $colBG           "188 220 231";          // Background colour setting
  
var $colTxt          "0 0 0";                // Text colour setting (black)
  
var $colBorder       "0 128 192";            // Border colour setting
  
var $charx           20;                     // Lateral space of each char
  
var $numCirculos     3;                      // Number of random circles



  //////////////////////////////////////////////////////////////////////
  //
  // No need to make any changes below here
  // 
  //////////////////////////////////////////////////////////////////////

  
var $logfile         "/tmp/bad_bot.log";     // Bad_Bot log file (brute force)
  
var $doBadBotLogging 0;                      // Boolean to see if we should log bad robot attempts (1 = Yes, 0 = No)
  
var $numChars        5;                      // Size of String: default 5 (in case a spambot tries to set size=0 parameter)
  
var $max_attempts    5;                      // Max number of allowed attempts (brute force)
                                                 // (slip-through attacks are more deadly so leave this relatively big)

  
var $session_label   'xyzpldlkjoj_23ljks';   // Session Code Label (change for yourself!)
  
var $post_label      'ljs_lj231vuewo10_m';   // Post Code Label (change for yourself!)
  
var $max_num_label   'max_attempts';         // Maximum Attempts Label (change for yourself!)
    



  
var $num_attempts 0;                      // Number of attempts they've already tried (brute force)
  
var $w            20;                     // Width of the image (automatically calculated below)
  
var $DEBUG        5;                      // Are we DEBUG'ing?
  
var $sessionCode  '';                     // Initialize the php cookie's session Code storage variable
  
var $postCode     '';                     // Initialize the user's posted Code storage variable

  
var $image_display_label  'display_image';        // Set display image variable label
  
var $image_size_label     'size';                 // Set image size variable label



  // Constructor; just starts the server-side cookie session
  
function vImage(){
    
// Initialize local variables to globals:
    
$this->logfile         $GLOBALS['logfile'];
    
$this->doBadBotLogging $GLOBALS['doBadBotLogging'];
    
$this->numChars        $GLOBALS['numChars'];
    
$this->max_attempts    $GLOBALS['max_attempts'];
    
$this->session_label   $GLOBALS['session_label'];
    
$this->post_label      $GLOBALS['post_label'];
    
$this->max_num_label   $GLOBALS['max_num_label'];

    
// Set the session to expire in 15 mins...
    //session_save_path(".");   // Save cookies in local directory?
    
session_cache_expire(15);
    
session_start();
  }


    
  
// Generate the text (string passcode)
  // Gerar is to generate in Portugese
  
function gerText($num){
    
// Check passed size of string to make sure it's bigger than min numChars
    
if ( ($num != '') && ($num $this->numChars) )
      
$this->numChars $num;

    
// To generate random strings
    
$this->texto $this->gerString();

    
// SET the code we just generated in their server-side cookie for later comparison
    
$_SESSION["$this->session_label"] = $this->texto;
  }




  
// Load the codes (postCode is what they guessed; sessionCode is what we set)
  
function loadCodes() {
    
$this->postCode    = isset($_POST["$this->post_label"])       ? $_POST["$this->post_label"]       : "";
    
$this->sessionCode = isset($_SESSION["$this->session_label"]) ? $_SESSION["$this->session_label"] : "";
  }


    
  
//////////////////////////////////////////////////////
  // Check the code; return true or false
  // Also, counter slip-through attempts by spambots in here!
  // (slipthrough spammers use a blank sessionCode in fake sessionID)
  //////////////////////////////////////////////////////
  
function checkCode() {
    if (isset(
$this->postCode))
      
$this->loadCodes();
    
    
// Some spammers got through with a blank code!
    
if (empty($this->sessionCode)) {
      
// Log slip-through attempts...
      
if ($this->DEBUG 0) {
    
$this->LogAttempt("slipthrough");
      }
      return 
false;
    }
    
    if (
$this->postCode == $this->sessionCode) {
      
// 2006-06-13: prevent piggy-backing (session hijacking) on a successful post attack
      // RESET the code before returning on a successful post 
      // Do this to prevent a piggy-backing attack
      
$this->gerText($this->numChars);

      
// Log successful attempts?
      
if ($this->DEBUG 3) {
    
$this->LogAttempt("success");
      }

      return 
true;
    } else {
      
// Log unsuccessful attempts?
      
if ($this->DEBUG 3) {
    
$this->LogAttempt("nomatch");
      }
      
// Counter against a potential brute force attack
      
$this->CounterBruteForce();
      return 
false;
    }
  }
  
  
//////////////////////////////////////////////////////
  // Counter Potential Brute Force Attacks:
  //////////////////////////////////////////////////////
  
function CounterBruteForce() {
    if(empty(
$_SESSION["$this->max_num_label"])) {
      
$_SESSION["$this->max_num_label"] = 1;
      
$this->num_attempts       1;
    } else {
      
$_SESSION["$this->max_num_label"]++;
      
$this->num_attempts++;
      
      
// if more than ($max_attempts) refreshes, block further refreshes
      // can be negated by connecting with new session id
      // could get round this by storing num attempts in database against IP
      // could get round that by connecting with different IP (eg, using proxy servers)
      // in short, there's little point trying to avoid brute forcing
      // the best way to protect against BF attacks is to ensure the dictionary is not
      // accessible via the web or use random string option
      
if($_SESSION["$this->max_num_label"] > $this->max_attempts) {
    
// RESET the code here immediately!
    
$this->gerText($this->numChars);
    
    
// depending on how rude you want to be :-)
    //ImageString($im,5,0,20,"bugger off you spamming bastards!",$red);

    // Possibly send em to bad_bot page?  Or log to a file???
    
if ($this->DEBUG 0) {
      
$this->LogAttempt("bad_bot");
    }
      }
    }
    
  }


  
// Log Bad_Bot Attempt!    
  
function LogAttempt($kind) {
    if ( 
$this->doBadBotLogging ) {
       
// Open the filehandle (append to end)
       
$fh fopen($this->logfile'a') or die ("Couldn't open $this->logfile\n");
       
fwrite($fh"$kind | "$_SERVER['REMOTE_ADDR'] ." | "date("Y-m-d H:i:s")  ." | "$this->num_attempts ." | Session:"$this->sessionCode  ." | Post:"$this->postCode ."\n");
       
fclose($fh);
    }
  }
  
    
  function 
showCodBox($mode=0,$extra=''){
    
$str "<input type=\"text\" name=\"$this->post_label\" ".$extra." > ";
    
    if (
$mode)
      echo 
$str;
    else
      return 
$str;
  }
  
  function 
showImage(){
    
    
    
$this->gerImage();
    
    
header("Content-type: image/png");
    
ImagePng($this->im);
    
  }
  
  function 
gerImage(){
    
// To calculate size to fit text
    
$this->= ($this->numChars*$this->charx) + 40// 5px de cada lado, 4px por char
    // To Create img
    
$this->im imagecreate($this->w$this->h); 
    
//to draw deep edge and
    
imagefill($this->im00$this->getColor($this->colBorder));
    
imagefilledrectangle $this->im11, ($this->w-2), ($this->h-2), $this->getColor($this->colBG) );

    
//        #desenhar circulos (to draw circles?)
    //        for ($i=1;$i<=$this->numCirculos;$i++) {
    //            $randomcolor = imagecolorallocate ($this->im , rand(100,255), rand(100,255),rand(100,255));
    //            imageellipse($this->im,rand(0,$this->w-10),rand(0,$this->h-3), rand(20,60),rand(20,60),$randomcolor);
    //        }
    
    //To write text
    
$ident 20;
    for (
$i=0;$i<$this->numChars;$i++){
      
$char substr($this->texto$i1);
      
$font rand(4,5);
      
$y round(($this->h-15)/2);
      
$col $this->getColor($this->colTxt);
      if ((
$i%2) == 0){
    
imagechar $this->im$font$ident$y$char$col );
      }else{
    
imagechar $this->im$font$ident$y$char$col );
      }
      
$ident $ident+$this->charx;
    }
    
  }
  
  function 
getColor($var){
    
$rgb explode(" ",$var);
    
$col imagecolorallocate ($this->im$rgb[0], $rgb[1], $rgb[2]);
    return 
$col;
  }
  
  function 
gerString(){
    
rand(0,time());
    
$possible="abcdefghijklmnopqrstuvwxyz1234567890";
    
$str "";
    while(
strlen($str)<$this->numChars)
      {
    
$str.=substr($possible,(rand()%(strlen($possible))),1);
      }
    
    
$txt $str;
    
    return 
$txt;
  }
// End vImage class






/////////////// Image Authentication Globals ///////////////
///// Image Authentication Header
$vImage = new vImage();

// Code submitted just tells us whether or not they've attempted to submit a code yet        
if (! isset( $code_submitted ) ) {
  
$code_submitted 0;
} else {
  
$vImage->loadCodes();
}


// Are we being called to show the image? 
if ( !empty($_GET["$vImage->image_size_label"]) ) {
  
$vImage->gerText($_GET["$vImage->image_size_label"]);
  
$vImage->showImage();
  exit();
}
//////////////////////////////////////////////////////////////////////





        
//////////////////////////////////////////////////////////////////////
// 
// Start Guestbook Output
// 
//////////////////////////////////////////////////////////////////////

/////////////// Parse The Input ///////////////
// Get our variables IF there was a post:
// 2007-06-13: Replaced $HTTP_POST_VARS with $_POST
if ( !empty( $_POST ) ) {
   
reset ($_POST);
   while (list (
$key$val) = each ($_POST)) {
      
// After hacking attempt, make <META tags illegal in all fields:
      
$val preg_replace("/<meta/i""<junk"$val); 

      
$FORM["$key"] = $val;
   }
   
   
// Strange!  PHP automatically escaped ' and " -- reverse it?
   
$FORM{'comments'} = isset($FORM{'comments'}) ? stripslashes($FORM{'comments'}) : "";

   
// Check the variables:
   
VerifyFormVariables();

   
// Make usable variables
   // Don't use automatic variables (e.g., $realname) since not secure (e.g., Meta tags deletion above)
   // 2007-06-13: added isset() checks
   
$name      = isset($FORM{'realname'})     ? $FORM{'realname'}     : "";
   
$email      = isset($FORM{'username'})     ? $FORM{'username'}     : "";
   
$url       = isset($FORM{'url'})          ? $FORM{'url'}          : "";
   
$city       = isset($FORM{'city'})         ? $FORM{'city'}         : "";
   
$state       = isset($FORM{'state'})        ? $FORM{'state'}        : "";
   
$country       = isset($FORM{'country'})      ? $FORM{'country'}      : "";
   
$referrer       = isset($FORM{'referrername'}) ? $FORM{'referrername'} : "";
   
//$comment      = $FORM{'comments'};    // Set in VerifyFormVariables() call above
   
$private       = isset($FORM{'private'})      ? $FORM{'private'}      : "";
   
$password       = isset($FORM{'password'})     ? $FORM{'password'}     : "";
   
$ip          getenv ("REMOTE_ADDR"); // get the ip number of the user 
   
$FORM{'ip'}      = $ip;

   
$theCode       $vImage->checkCode();

   
// Print the Blank Response Subroutines in case no name or comment:
   
if (!$theCode || !$comment || !$name) {
      
$code_submitted 0;
      
MissingInfo();
   }

   
// Actual Output of Comments/Entries Now (if not exited)
   
WriteDataFile();

   
// Mail a copy of the comment to us
   
if ($mail == '1') {
     
SendMeMail();
   }

   
// Mail a copy of the comment to the signer
   
if ($remote_mail == '1' && $email) {
     
SendThemMail();
   }

   
// Print Out Initial Output Location Heading
   
if ($redirection == '1') {
      
// Redirect header
      
header ("Location: $guestbookurl");
      exit;  
// Make sure that code below does not get executed when we redirect.
   
} else { 
      
No_Redirection();
   }
}







// Keep fxns inline for ease of distribution
//require ("guestbook-fxns.inc");

//////////////////// Start Output Functions ////////////////////
//
//


//
// Fxn to Verify Form Variables
//
function VerifyFormVariables() {
   
// Declare my globals (so it doesn't just create a new, local var)
   
global $FORM$orig_comments$comment$guestbookurl;
   global 
$date$shortdate$cgiurl$uselog$guestlog;
   global 
$defaultpassword;                // 2007-01-31: Thanks to Curran Nachbar Schiefelbein
   
global $allow_html$line_breaks;       // 2008-02-07: using it but not added in!

   // 2007-06-13: added isset() check
   
if ( isset($FORM{'url'}) && preg_match("%^http://$%",$FORM{'url'}) ) {
      
$FORM{'url'} = "";
   }

   
// Fix the $referrername variable's sentence terminator:
   // 2007-06-13: added isset() check
   
if ( isset($FORM{'referrername'}) && preg_match("%[^\!]$%",$FORM{'referrername'})) {
      
$FORM{'referrername'} .= ".";
    }

   
// Should we allow html tags?
   
if (isset($allow_html) && $allow_html == 0) {
      
// Could replace all < & > with &gt; & &lt; instead (to keep context?)
      
$FORM{'comments'} = preg_replace("%<([^>]|\n)*>%"""$FORM{'comments'}); 
   }

   
/*
   // Replace all remaining < and > characters
   if (isset($allow_html) && $allow_html == 0) {
      $FORM{'comments'} = preg_replace("%<%", "&lt;", $FORM{'comments'}); 
      $FORM{'comments'} = preg_replace("%>%", "&gt;", $FORM{'comments'}); 
   }
   */

   
if (isset($line_breaks) && $line_breaks == 1) {
      
$FORM{'comments'} = preg_replace("%\cM\n/<br>\n%g","",$FORM{'comments'});
   }

   if ( isset( 
$FORM{'private'} ) ) {
      if (!
$FORM{'password'}) {
     
$FORM{'password'} = $defaultpassword;
      }
    
      
// Parse comment for weird characters:
      // Parse for quotes (all varieties) and replace with \'
      // Strange, had to separate these out because of multiple \\'s in comment
      // Order is important
      
$FORM{'comments'} = preg_replace("%['\"]%""\\'"$FORM{'comments'}); 
      
$FORM{'comments'} = preg_replace("%[\`]%""\\'"$FORM{'comments'}); 
      
      
// Parse html out of private comments by default
      
$FORM{'comments'} = preg_replace("%<([^>]|\n)*>%"""$FORM{'comments'}); 
      
      
// Parse for ^M's (the \r\n that Windows doesn't understand)
      
$FORM{'comments'} = preg_replace("%\r?\n%""\\n"$FORM{'comments'}); 

      
$orig_comments $FORM{'comments'};
      
$password $FORM{'password'};
      
$comment = <<<PRIVATECOMMENT
<a href="$guestbookurl" onClick="passed = '$password'; commentString = '$orig_comments'; var prompted = prompt(promptString1, promptString2); if (prompted == passed) {alert(commentString);} else if (prompted != null) {alert(alertString);} return false;">Private Guestbook Comment</a><br>
PRIVATECOMMENT
      ;
      
// Hose trailing newline from above <<P
      
rtrim($comment);
    } else {
      
// Parse for ^M's (the \r\n that Windows doesn't understand)
      
$FORM{'comments'} = preg_replace("%\r?\n%""<BR>"$FORM{'comments'}); 
      
$orig_comments $FORM{'comments'};
      
$comment $FORM{'comments'};
    }

}



//
// Fxn to show missing information:
//
function MissingInfo() {
   
// Declare my globals (so it doesn't just create a new, local var)
   
global $name$email$url$city$state$country$referrer$comment$private$password$ip;
   global 
$date$shortdate$uselog$bcol;
   global 
$guestbookurl$cgiurl$homeurl$homepageText;
   global 
$vImage;



   
// What's missing?
   
if (!$comment) {
      
$missingitem "The Comments Section";
   } elseif (!
$name) {
      
$missingitem "Your Name";
   
//////////////////////////////////////////////////////////////////////
   // 2006-07-01: This HAS to be the LAST CHECKED item otherwise it'll
   //             always report that incorrect authentication code was
   //             entered since we re-set authentication code even on
   //             a successful submission (which was done to prevent
   //             piggy-back/session hijacking attacks by spambots).
   //////////////////////////////////////////////////////////////////////
   
} elseif (!$vImage->checkCode()) {
      
$missingitem "Correct Authentication Code";
   }


   
// Print the form:
   
print <<<MISSINGINFO
<html>
<head><title>
$missingitem wasn't entered</title></head>
<body>

<CENTER>
<h1>
$missingitem wasn't entered!</h1>
</CENTER>

How could you forget to enter 
$missingitem???  Are you taking drugs??  
Do I have to give you that lecture <i>again</i>??  Try it again... 
and for Pete's sake, get it right this time, willya?!?! 
<p>
<HR>


<table>
<TR>
   <TD><FONT FACE="Verdana,Arial" SIZE=+1 COLOR=EF0000><B>Enter Info Below:</B></FONT></TD></TR>
<TR>
   <TD>&nbsp;&nbsp;&nbsp;Fill in the blanks to add to our guestbook.
     Please enter at least your name along with the correct
     authentication code and your comment(s)... Thanks!
</table>
MISSINGINFO
    ;

   
// Print the actual form now
   
$foo  $bcol;
   
$bcol "D0D0D0";
   
PrintAddForm();
   
$bcol  $foo;

   print <<<MISSINGINFO
<p>

<font size=-1>
    <hr>
    * <a href="
$guestbookurl">Back to the Guestbook Entries</a><br>
    * <a href="
$homeurl">Back to $homepageText</a><br>

<br>
</font>

</body></html>
MISSINGINFO
    ;

    
// Log The Error
    
if ($uselog == '1') {
    
LogIt("$missingitem");
    }

    exit;
}



//
// Fxn to log the entry or error:
//
function LogIt($field) {
   
// Declare my globals (so it doesn't just create a new, local var)
   
global $name$email$url$city$state$country$referrer$comment$private$password$ip;
   global 
$date$shortdate$cgiurl$uselog$guestlog;
   global 
$tmpguestlog$moderated;

   
$log_type $field;

   if (
$moderated) {
      
$filename $tmpguestlog;
   } else {
      
$filename $guestlog;
   }

   
// Don't create the logfile if it doesn't exist already
   //if (!file_exists($filename)) {
   //   return;
   //}

   
$LOG fopen ("$filename""a");

   if (
$log_type == 'entry') {
      
fwrite($LOG"$ip - [$shortdate]<br>\n");
   } elseif (
$log_type == 'Correct Authentication Code') {
      
fwrite($LOG"$ip - [$shortdate] - ERR: Invalid Authentication Code<br>\n");
   } elseif (
$log_type == 'Your Name') {
      
fwrite($LOG"$ip - [$shortdate] - ERR: No Name<br>\n");
   } elseif (
$log_type == 'The Comments Section') {
      
fwrite($LOG"$ip - [$shortdate] - ERR: No Comments<br>\n");
   }

   
fclose($LOG);  
}



//
// Fxn to Write Data File
//
function WriteDataFile() {
   
// Declare my globals (so it doesn't just create a new, local var)
   
global $FORM$comment,$guestbookdata;
   global 
$name$email$url$ip;
   global 
$date$shortdate$cgiurl$uselog$guestlog;
   global 
$tmpguestbookdata$moderated;

   
$how $FORM{referrername};

   
$from "";
   if ( 
$FORM{'city'} ){
       
$from .= $FORM{'city'} . ",";
   }
   if ( 
$FORM{'state'} ){
       
$from .= " " $FORM{'state'};
   }
   if ( 
$FORM{'country'} ){
        
$from .= " " $FORM{'country'};
   }


   if (
$moderated) {
      
$filename $tmpguestbookdata;
   } else {
      
$filename $guestbookdata;
   }

   
// Just add to end of guestdata.txt now:
   // Bkp current data

   // Now write data
   
$OUT fopen ("$filename""a") or die ("Can't Open $filename!\n");

   
fwrite($OUT"--------------------------------------------------\n");
   
fwrite($OUT"name:\t$name\n");
   
fwrite($OUT"email:\t$email\n");
   
fwrite($OUT"url:\t$url\n");
   
fwrite($OUT"date:\t$date\n");
   
fwrite($OUT"how:\t$how\n");
   
fwrite($OUT"from:\t$from\n");
   
fwrite($OUT"comment:\t$comment\n");
   
fwrite($OUT"ip:\t$ip\n");
   
fwrite($OUT"END_GUESTBOOK_ENTRY\n");

   
fclose($OUT);  

   
// Log The Entry
   
if ($uselog == '1') {
      
LogIt('entry');
   }

}



//
// Fxn to print the confirmation
//
function No_Redirection() {
   
// Declare my globals (so it doesn't just create a new, local var)
   
global $name$email$url$city$state$country$referrer$comment$private$password$ip;
   global 
$date$shortdate$cgiurl$uselog$guestlog;
   global 
$guestbookurl;

   
// Print Beginning of HTML
   //print "Content-Type: text/html\n\n";
   
print "<html><head><title>Thank You</title></head>\n";
   print 
"<body><h1>Thank You For Signing The Guestbook</h1>\n";

   
// Print Response
   
print "Thank you for filling in the guestbook.  Your entry has\n";
   print 
"been added to the guestbook.<hr>\n";
   print 
"Here is what you submitted:<p>\n";
   print 
"<b>".$FORM{'comments'}."</b><br>\n";

   if (
$FORM{'url'}) {
      print 
"<a href=\"$url\">$name</a>";
   }
   else {
      print 
"$name";
   }

   if ( 
$FORM{'username'} ){
      if (
$linkmail == '1') {
         print 
" &lt;<a href=\"mailto:$email\">";
         print 
"$email</a>&gt;";
      }
      else {
         print 
" &lt;$email&gt;";
      }
   }

   print 
"<br>\n";

   if ( 
$FORM{'city'} ){
      print 
"$city,";
   }

   if ( 
$FORM{'state'} ){
      print 
$state";
   }

   if ( 
$FORM{'country'} ){
      print 
$country";
   }

   print 
" - $date<p>\n";

   
// Print End of HTML
   
print "<hr>\n";
   print 
"<a href=\"$guestbookurl\">Back to the Guestbook</a>\n";
   print 
"- You may need to reload it when you get there to see your\n";
   print 
"entry.\n";
   print 
"</body></html>\n";

   exit;
}



//
// Fxn to send a confirmatory email to us
//
function SendMeMail() {
  
// Declare my globals (so it doesn't just create a new, local var)
  
global $name$email$url$city$state$country$referrer$comment$private$password$ip;
  global 
$date$recipient$orig_comments;

  if (!
$email) {
    
$email $recipient;
  }

  
// Set the headers:
  
$headers  "";
  
$headers .= "From: $name <$email>\n";
  
$headers .= "Reply-to: $name <$email>\n";
  
$headers .= "Return-Path: <$recipient>\n";  // Return path for errors
  
$headers .= "X-Sender: <$recipient>\n";
  
  
// Subject
  
$subject "New Guestbook Entry!";
  
$subject rtrim($subject);
  
  
// Message
  
$message  "";
  
$message .= "You have a new entry in your guestbook:\n\n";
  
$message .= "------------------------------------------------------\n";
  
$message .= "$orig_comments\n";
  
$message .= "-- $name <$email> from $ip\n";
  
   if ( 
$city ){
     
$message .= "$city, ";
   }

   if ( 
$state ){
     
$message .= "$state ";
   }

   if ( 
$country ){
     
$message .= "$country";
   }

   
$message .= " - $date\n";
   
$message .= "------------------------------------------------------\n";

   
// Add in the other fields:
   
$message .= "URL: $url\nReferrer: $referrer\nPrivate/Password: $private$password\n";

   
// Mail it out:
   
mail($recipient$subject$message$headers);
}



//
// Fxn to send the signer a confirmatory email
//
function SendThemMail() {
   
// Declare my globals (so it doesn't just create a new, local var)
   
global $name$email$url$city$state$country$referrer$comment$private$password$ip;
   global 
$date$recipient$orig_comments;

   
// Reset recipient variable (LOCALLY only; not the global one):
   
$sender    $recipient;
   
$to        $email;

   
// Set the headers:
   
$headers  "";
   
$headers .= "From: $sender\n";
   
$headers .= "Return-Path: <$sender>\n";  // Return path for errors
   
$headers .= "X-Sender: <$sender>\n";
  
   
// Subject
   
$subject "New Guestbook Entry!";
   
$subject rtrim($subject);
  
   
// Message
   
$message  "";
   
$message .= "Thank you for adding the following entry to our guestbook:\n\n";
   
$message .= "------------------------------------------------------\n";
   
$message .= "$orig_comments\n";
   
$message .= "-- $name <$email> from $ip\n";
   
   if ( 
$city ){
     
$message .= "$city, ";
   }
   
   if ( 
$state ){
     
$message .= "$state ";
   }
   
   if ( 
$country ){
     
$message .= "$country";
   }
   
   
$message .= " - $date\n";
   
$message .= "------------------------------------------------------\n";
   
   
// Mail it out:
   
mail($to$subject$message$headers);
}
//////////////////// End Output Functions ////////////////////




//////////////////// Start Display Functions ////////////////////
//
// Fxn to Print out $number formatted entries per page:
function PrintEntries($num=0) {
   
// Declare my globals (so it doesn't just create a new, local var)
   
global $no_entries$number$start$numpages$startEntry$f$bg$postgif$transpgif;

   
// Don't print more than total number of entries:
   
$max $number*$start;
   
$max = ($max $no_entries) ? $no_entries $max;

   
// If we want to print out all the entries (e.g., for allguests.phtml)
   // 2007-06-13: added isset() check
   
if ( isset($num) && $num ) {$max $num;}

   for (
$x=$startEntry$x<=$max$x++) {
    
// Could add Entry # $x later or use $x to print a certain # of entries per page
    // Copy over Entry #$x's array:
    
global ${"e$x"};
    
$val = ${"e$x"};
    
    
// Setup variables
        // 2007-04-11: Added rel="nofollow" to links to prevent spiders from following links in order to discourage spammers (@REFERENCE: http://www.textlinksguide.com/pagerank.html)
    
$name $val[1];
    if ( !
preg_match("/^\s*$/"$val[3]) ) {$name "<a rel=\"nofollow\" target=\"_new\" href=\"$val[3]\">$val[1]</a>";}
    
    
$email "";
    
$mangled_email preg_replace("/\@/"," at "$val[2]);
    
$mangled_email preg_replace("/\./"," dot "$mangled_email);
    
//echo "<b>$mangled_email</b>";
    //#if ( !preg_match("/^\s*$/", $val[2]) ) {$email = "&lt;<a href=\"mailto:$val[2]\">$val[2]</a>&gt;";}
    
if ( !preg_match("/^\s*$/"$val[2]) ) {$email "&lt;<a href=\"mailto:$mangled_email\">$mangled_email</a>&gt;";}
    
    
    
// Big Print Job:
    
if ($f == "Simple") {
      
//echo "Chose Simple";
    
print <<<EOP
<!-- BEGIN $val[1] -->
  <tr><td></td><td>
<TABLE WIDTH=700 BORDER=0 CELLPADDING=2 CELLSPACING=0>
<TR>
   <TD  COLSPAN=2 BGCOLOR=D0D0D0><b>
$name</b> $email</TD></TR>
<TR>
   <TD  COLSPAN=2 BGCOLOR=D0D0D0><font ace=arial size=3>visited us on 
$val[4]</font></TD></TR>
<TR>
   <TD BGCOLOR=D0D0D0><font ace=arial size=3>
$val[5]</font></TD>
   <TD BGCOLOR=EFEFEF ALIGN=RIGHT><font color=#000099><font ace=arial size=3>
$name of $val[6] also took time to comment:</font></TD></TR>
<TR>
   <TD BGCOLOR=EFEFEF colspan=2><br>
$val[7]
</TABLE>
<BR><BR>
  </td></tr>
<!-- END 
$val[1] -->



EOP;
    } else if (
$f == "Standard") {
      
//echo "Chose Standard";
    
print <<<EOP
<!-- BEGIN $val[1] -->
  <tr><td></td><td>
<BR>
<small><u><i>Record No.</i></u>:  <b>
$x</b></small><P>
<B>
$val[7]</B><BR>
$name $email
$val[6] -- $val[4]
<HR noshade>
  </td></tr>
<!-- END 
$val[1] -->



EOP;
    } else {
      
//echo "Chose Default";
    
print <<<EOP
<!-- BEGIN $val[1] -->
  <tr>
  <td valign=top align=right><font face=times size=2><b>
$x.</b></font></td>
  <td>
    <TABLE CELLPADDING="0" CELLSPACING="0" BORDER="0" BGCOLOR="black" WIDTH="700">
      <TR><TD bgcolor=black><IMG SRC="
$transpgif" height=1></TD></TR>
      <TR>
    <TD>
      <TABLE CELLPADDING="2" CELLSPACING="1" BORDER="0" BGCOLOR="black" WIDTH="100%">
        <TR BGCOLOR="#99CCCC">
        <TD vALIGN="top" colspan=2>
        <TABLE>
          <TR><TD vALIGN="top">
        <IMG SRC="
$postgif" WIDTH="27" HEIGHT="13">
          </TD>
          <TD vALIGN="top">
        <FONT SIZE="3" FACE="Times" color="#000000">
        <B>
$name $email</B>
        </FONT><BR>
        <FONT SIZE="1" COLOR="#800080" FACE="Verdana, Arial">
        visited us from 
$val[6] on $val[4] $val[5]
        </FONT>
          </TD>
          </TR>
        </TABLE>
        </TD>
        </TR>

        <TR BGCOLOR="#F7F7F7">
        <TD ALIGN="left" VALIGN="top" COLSPAN=2>
        <TABLE CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
          <TR>
        <TD>
        <BR>
        <FONT FACE="arial" SIZE="2">
        
$val[7]
        </FONT>
        </TD>
          </TR>
        </TABLE>
        </TD>
            </TR>
          </TABLE>
    </TD>
      </TR>
    </TABLE>
  </td></tr>
<!-- END 
$val[1] -->



EOP;
    }


   } 
// End FOR loop

// End Fxn Defn.








// Fxn to print out navbar for entries:
function PrintNavControl() {
   
// Declare my globals (so it doesn't just create a new, local var)
   
global $no_entries$number$start$numpages$startEntry$f$bg$cgiurl;

   print 
"<tr><td></td><td align=center>\n";
   print 
"<table width=100%><tr><td align=left><font face=arial size=2><a href='$cgiurl#add'><b>ADD an entry</b></a></font></td>\n";

   print 
"<td align=center><font face=times size=3>
     &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
     &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>\n"
;
   
// Print Previous Button/Image:
   
$prev $start 1;
   if (
$start 1) {print "<a href='$cgiurl?start=$prev&number=$number&bg=$bg&f=$f'>&lt;&lt;</a>&nbsp;\n";}
   print 
"</b>[<b>&nbsp;";
   for (
$x=1$x<=$numpages$x++) {
    
// Don't link current page ($start)
    
if ($x == $start) {
       print 
"<font color=red>$x</font>&nbsp;";
    } else {
       print 
"<a href='$cgiurl?start=$x&number=$number&bg=$bg&f=$f'>$x</a>&nbsp;";
    }
   }
   print 
"</b>]<b>&nbsp;";
   
// Print Next Button/Image:
   
$next $start 1;
   if (
$start $numpages) {print "&nbsp;<a href='$cgiurl?start=$next&number=$number&bg=$bg&f=$f'>&gt;&gt;</a>\n";}
   print 
"</b></font></td>\n";

   print 
"<td align=right><font face=times size=2>Entries Per Page: 
     <a href='
$cgiurl?number=10&startEntry=$startEntry&bg=$bg&f=$f'>10</a>&nbsp;
     <a href='
$cgiurl?number=20&startEntry=$startEntry&bg=$bg&f=$f'>20</a>&nbsp;
     <a href='
$cgiurl?number=50&startEntry=$startEntry&bg=$bg&f=$f'>50</a>&nbsp;
     </font></td></tr></table>\n"
;
   print 
"</td></tr>\n";

}



// Fxn to print customization form
function PrintCustomControl() {
   
// Declare my globals (so it doesn't just create a new, local var)
   
global $no_entries$number$start$numpages$startEntry$f$bg$bgcolours$formats$bcol$goblack;
   global 
$cgiurl;
   
   
// Make Drop Downs:
   
$bg_drop '<select name="bg">';
   
$f_drop  '<select name="f">';
   while (list (
$key$val) = each ($bgcolours)) {
     
//echo "$key => $val<br>";
     
if ($val == $bg) {
       
$bg_drop .= "<option selected value=\"$val\">$val";
     } else {
       
$bg_drop .= "<option value=\"$val\">$val";
     }
   }
   while (list (
$key$val) = each ($formats)) {
     
//echo "$key => $val<br>";
     
if ($val == $f) {
       
$f_drop .= "<option selected value=\"$val\">$val";
     } else {
       
$f_drop .= "<option value=\"$val\">$val";
     }
   }
   
$bg_drop .= '</select>';
   
$f_drop  .= '</select>';
   
//echo "bg: $bg_drop<BR>format: $f_drop<BR>";

   
   // Customization stuff here:
   
print <<<EOP
<br><br>
<table width=100%>
<tr>
<td><font face="arial" size="2"><b>Select Format:</b></font></td>
<td><font face="arial" size="2"><b>Background:</b></font></td>
<td align=right rowspan=2 valign=middle>
<!--
<a href="http://www.sethi.org/guestbook/allguests.phtml?bg=<?php print(
$bg)?>&f=<?php print($f)?>">
<font face="times" size=4 color=blue><b>
All 
$no_entries entries
-->
<a href="
$cgiurl?bg=$bg&f=$f">
<font face="arial" size=2 color=blue><b>
Back to Guestbook FrontPage
</b></font>
</td>
</tr>

<tr>
<form method=GET action="
$cgiurl">
<input type="hidden" name="number" value="
$number">
<input type="hidden" name="startEntry" value="
$startEntry">
<td align=left valign=top>
$f_drop
</td>

<td align=left valign=top>
$bg_drop
&nbsp;
<input type=image name="change" alt="Change my scheme!" 
  SRC="
$goblack" border="0"> 
</td>
</form>

</tr>

</table>
EOP;

}
//////////////////// End Display Functions ////////////////////


?>

<html>
<?php $version "2.5"?>


<!-- ================== mainScriptStuff ================== -->
<?php

//////////////////////////////////////////////////////////////////////
//
// No need to make any changes below here
// 
//////////////////////////////////////////////////////////////////////



/////////////// Set Some Variables ///////////////
// Figure out the browser type:
$browser=0;
// 2007-06-13: replaced $HTTP_USER_AGENT with $_SERVER['HTTP_USER_AGENT'] and added isset() check
if( isset($_SERVER['HTTP_USER_AGENT']) && eregi("MSIE",$_SERVER['HTTP_USER_AGENT']) ) {$browser=1;}

// Set width of private comment:
if ($browser) {
  
// For M$ IE
  
$pwidth "525";
} else {
  
// For Nutscrape Navigator
  
$pwidth "530";
}
/////////////// Set Some Variables ///////////////





//////////////////////////////////////////////////
// Start actual program
//////////////////////////////////////////////////

// Read in the guestbook file into a Variable (instead of an array):
if (file_exists($datafile)) {
   
$fcontents join''file($datafile) );
} else {
   
$fcontents "";
}

// Split input file into entries:
$entries_arr split"$file_splitter"$fcontents);


// What's the entry order we should use?
if ($entry_order) {
   
$entries_arr array_reverse($entries_arr);
   
array_unshift($entries_arr"");
   
$foobar array_pop($entries_arr);
}

// How many elements do we have?
$no_entries sizeof($entries_arr) - 1;




// Number of pages:
$numpages floor($no_entries/$number);
if (
$no_entries $number) {$numpages++;}

///// $start and $startEntry go together and after the others /////
// $start is starting page #
// 2007-06-13: added isset() checks
if ( !isset($start) ) {
   
$start 1;
   
$firstTime 1;
   if ( isset(
$startEntry) ) {
      
$firstTime 0;
      
$start floor( ($startEntry-1)/$number );
      if (
$start == 1) {$startEntry 1;}
   }
}

// Starting entry number:
$startEntry = ($number * ($start 1)) + 1;
///// $start and $startEntry go together and after the others /////






//////////////////// Get Individual Entries ////////////////////
// Print out each of the entries here:

// Parse out entries_array (but skip the first, 0th, entry since it's blank)
for ($x=1$x<=$no_entries$x++) {
    
$entry_arr split("\n"$entries_arr[$x]);
    
// Now split each entry into individual lines
    
$no_data sizeof($entry_arr) - 1;
    
// Get the 7 variables (name, email, url, date, how, from, comment) in that order
    
next($entry_arr); // Skip the 0th entry (it's blank)
    
for($y=2;$y<$no_data;$y++) {
        list (
$key$val) = each ($entry_arr);
    
// $val is "name: Sabrina", etc.
    // $data_arr is now ("name", "Sabrina")
        
$data_arr split(":\s*"$val2);
    
// The value is in 2nd element, $data_arr[1] == Sabrina
    
$values[$y-1] = trim($data_arr[1]);
    }
    
/////////////// Print out the entry now: ///////////////
    //echo "Entry #$x<BR>";
    //echo "Name:      $values[1]<BR>";
    //echo "Email:     $values[2]<BR>";
    //echo "URL:       $values[3]<BR>";
    //echo "Date:      $values[4]<BR>";
    //echo "How:       $values[5]<BR>";
    //echo "From:      $values[6]<BR>";
    //echo "Comment:   $values[7]<BR>";
    //echo "<hr>";
    /////////////// Print out the entry now: ///////////////


    /////////////// Store Entry in an Array ///////////////
    
${"e$x"} = $values;
}
//////////////////// Get Individual Entries ////////////////////







?>
<!-- ================== /mainScriptStuff ================== -->




  <head>
    <title><?php print($titleTag2);?></title>
    <?php if ($basehref) print("<base href=\"$basehref\">\n"); ?>
    <meta http-equiv="expires" content="Thu, 01-Jan-1970 00:00:01 GMT">
    <meta name="description" content="<?php print($description);?>">
    <meta name="keywords" content="<?php print($keywords);?>">
    <!-- ================== javascripts ================== -->
    <?php
    
if ( $includeJavascript && file_exists($jsfilepath) ) {
    echo 
"<script language=javascript src=\"$jsfile\"></script>";
    }
    
?>
    <script language="javascript">
    // Disable Right Click:
    disableRightClick = 1;
    var promptString1 = '<?php print($promptString1?>';
    var promptString2 = '<?php print($promptString2?>';
    var alertString   = '<?php print($alertString?>';
    </script>
    <script language="javascript">
    // Preload transparent pixel:
    img1     = new Image();
    img1.src = "<?php print($transpgif); ?>";
    img2     = new Image();
    img2.src = "<?php print($postgif); ?>";
    img3     = new Image();
    img3.src = "<?php print($goblack); ?>";
    </script>
    <!-- ================== /javascripts ================== -->
  </head>





<body bgcolor="<?php print($bg)?>" LEFTMARGIN="0" TOPMARGIN="0" MARGINHEIGHT=0 MARGINWIDTH=0>





<!-- ================== title ================== -->
<!-- START Header Table -->
<?php PrintTitleHeader(); ?>
<!-- END Header Table -->

<br>
<br>
<!-- ================== /title ================== -->





<!-- ================== addFormAndIntro ================== -->
<?php
// Show Intro and AddForm ONLY on first viewing of page:
if ($firstTime == 1){
?>

<a name="add"></a>
<!-- ================== intro ================== -->
<table cellpadding=3>
<tr><td>
<font face=arial size=2>
<?php print($titleBody)?>  
</font>
</td></tr>
</table>
<!-- ================== /intro ================== -->



<!-- ================== addForm ================== -->
<hr align=center width=50%>

<?php PrintTopNav();?>

<?php PrintAddForm();?>

<!-- ================== /addForm ================== -->



     <table>
       <tr>
       <td valign=top><small><B>Note</B>: &nbsp;</small></td>
       <td>
       <font size="-1">
     <ul>
       <li>Please fill in the blanks to add to our guestbook.
         <br />Also, <i><u>Private Guesbook Comments</i></u>
         require both a password and a JavaScript enabled browser.
       <li><!-- If you just added a comment, you might have to hit Reload/Refresh to see your new entry. -->
         <b>Please note: our guestbook is now moderated by a live
         human!</b>
         <br />
         This means that your entry might be edited or deleted
         before it is approved for permanent addition to our
         guestbook. 
         <!--
         This means that your entry will not appear
         until a live human being has approved it for addition to
         our guestbook.
         -->
       <li>Please have a look at the
         <a href="<?php print($guestlogurl?>">logs</a> if you'd like to see the
         corresponding domains for these entries.
       <li>In addition, we now use the <i>rel="nofollow"</i>
         attribute in all submitted links to discourage spambots.
       <li><b>Click <a target=_new href="<?php print($downloadLink?>">here</a> to
         download the source code for this guestbook.</b>
     </ul>
       </font>
       </td>
       </tr>
    </table>


    <P>
    <hr size=3 noshade>
    <P>

<?php
}
?>
<!-- ================== /addFormAndIntro ================== -->


    


<CENTER>
<!-- ================== superSetTable ================== -->

<!-- This anchor needs to be before the table for some reason -->
<a name="entries"></a>

<table align=center cellpadding=5 cellspacing=1 border=0>

<!--startOfEntries-->
<?php 

// Print Nav Bar:
PrintNavControl();


// Print out all the entries:
//PrintEntries($no_entries); 
// Print out $number entries to a page:
// Leave $num undefined for default (or passed in) # of entries per page
// 2007-06-13: added isset() check:
if ( isset($num) ) {
  
PrintEntries($num);
} else {
  
PrintEntries();
}


// Print Nav Bar:
PrintNavControl();

// Print Control Stuff:
echo "<tr><td></td><td>";
  if (
$multi_format) {
      
PrintCustomControl();
  }
echo 
"</td></tr>";

?>
<!--endOfEntries-->

</table>
<!-- ================== /superSetTable ================== -->
</CENTER>









<!-- ================== footer ================== -->
<?php 
if ( $includeFooterNavbar && file_exists($navbarpath) ) {
   include(
"$navbarpath");
}
?>

<!--
<a href="../">Back to The Sethi Family HomePage</a><br>
-->
<!-- ================== /footer ================== -->


  </body>
</html>