<?

/*

PHP-based guestbook, made by mathijssch@gmail.com

Changelog:
09-09-08: 0.4 Fixed bug which allowed empty messages to be posted
23-05-08: 0.3 Fixed XSS bug where non UTF-8 encoded input would not be stripped correctly (thanks to parkinm)
15-01-08: 0.2 Some XSS bugs fixed (thanks to fitsec)
13-01-08: 0.1 First version

NOTE: This file requires a guestbook.inc.php file with $host,$user,$pass,$db
NOTE2: The version on mathijs.info uses a custom CSS stylesheet: http://mathijs.info/css/guestbook.css and matweb.css

*/

// determine what to do
switch($_POST['action'])
{
    case 
"":
        
show_guestbook();
        break;
    case 
"add":
        
add_entry($_POST,$_SERVER);
        
show_guestbook();
        break;
    default:
        die(
"<p>Please do not fiddle with it!</p>");
}

// this function handles all database transactions
function database_transaction($query)
{
    require(
"guestbook.inc.php");

    
// try to connect to specified MySQL-database
    
$con mysql_connect($host,$user,$pass);
    if (!
$con)
      {
          die(
'<p>Could not connect: ' mysql_error()."</p>");
      }

    
// try to select the specified database
      
$try mysql_select_db($db$con);
      if (!
$try)
    {
          die(
'<p>Could not select database: ' mysql_error()."</p>");
      }

    
// execute query
    
$result mysql_query($query);
    if (!
$result)
    {
        die(
'<p>Could not process query: ' mysql_error()."</p>");
      }

    
// close the MySQL-connection
    
mysql_close($con);

    
// give back the results
    
return $result;
}

// this function adds an entry to the guestbook table
function add_entry($POST,$SERVER)
{
    
// check if correct captcha value is entered (question is "Adam and ...")
    
if(!strcmp(strtolower($POST['captcha']),"eve")==0)
        die(
"<p>Please fill in the correct answer to the safety question!</p>");

    
// check if required fields are entered
    
if($POST['name']==""||$POST['message']=="")
        die(
"<p>Please enter a name and message!</p>");

    
// check variable lengths
    
if((strlen($POST['name'])>50)||(strlen($POST['email'])>50)||(strlen($POST['homepage'])>50)||(strlen($POST['message'])>500))
        die(
"<p>One or more variables too long!</p>");

    
// check name
    
if(ereg('[^A-Za-z]',$POST['name']))
        die(
"<p>Name can only contain letters!</p>");
    
$name $POST['name'];

    
// check message, abort if nothing is left after filtering
    // also to be sure stripping functions work properly, force utf-8 encoding
    
$message sanitize_input(utf8_encode($POST['message']));
    if(!
strlen(trim($message))>0)
        die(
"<p>Illegal input found in message, or no message entered at all!</p>");

    
// check homepage
    
if($POST['homepage']<>""&&!verify_url($POST['homepage']))
        die(
"<p>Please enter a valid URL, including http(s)://, as homepage (or none at all)!</p>");
    
$homepage htmlspecialchars($POST['homepage']);

    
// check e-mail address
    
if($POST['email']<>""&&!verify_email($POST['email']))
        die(
"<p>Please enter a valid e-mail address (or none at all)!</p>");
    
$email htmlspecialchars($POST['email']);

    
// fill non-user-input variables
    
$time date("U");
    
$ip htmlspecialchars(sanitize_input($SERVER['REMOTE_ADDR']));

    
// check if user isn't flooding (wait 30 seconds)
    
$lastentry mysql_result(database_transaction("SELECT MAX(time) FROM guestbook_entries WHERE ip='$ip'"),0);
    if((
$time-$lastentry)<30)
        die(
"<p>Please wait a minute before posting again!</p>");

    
// put the data in the table
    
database_transaction("INSERT INTO `guestbook_entries` VALUES ('0','$ip','$time','$name','$homepage','$email','$message');");
}

function 
sanitize_input($input)
{
    if(
get_magic_quotes_gpc())
    {
        
$input stripslashes($input);
    }
    
//check if this function exists
    
if(function_exists("mysql_real_escape_string"))
    {
        
// try to connect to specified MySQL-database
        
require("guestbook.inc.php");
        
$con mysql_connect($host,$user,$pass);
        if (!
$con)
        {
            die(
'<p>Could not connect: ' mysql_error()."</p>");
          }
        
$input mysql_real_escape_string($input);
        
mysql_close($con);
    }
    
//for PHP version < 4.3.0 use addslashes
    
else
    {
        
$input addslashes$input );
    }
    return 
strip_tags($input);
}

function 
verify_url($url)
{
    
// check if URL is valid and the hostname resolves to an IP-address
    
return gethostbynamel(parse_url($url,PHP_URL_HOST));
}

function 
verify_email($email)
{
    
// check if valid format is entered
    
list($username$domain) = split("@"$email);
    if((
strlen($username)>0)&&(strlen($domain)>0))

    
// check if domain really has a MX-record in the DNS (if it is a mailserver)
        
return checkdnsrr($domain"MX");
    else
        return 
false;
}

function 
show_guestbook()
{
    
// the HTML-code for the form
    
?>
    <div class="guestbook">
        <form method="post" action="">
            <fieldset>
                <legend>Add message to guestbook</legend>
                <input type="hidden" name="action" value="add"></input>
                <p><label for="name">Name</label><input type="text" size="20" name="name" maxlength="50"></input>*</p>
                <p><label for="email">Email</label><input type="text" size="20" name="email" maxlength="50"></input></p>
                <p><label for="homepage">Homepage</label><input type="text" size="20" name="homepage" maxlength="50"></input></p>
                <p><label for="message">Message</label><textarea rows="5" cols="40" name="message" maxlength="500"></textarea>*</p>
                <p><label for="captcha"><i>Adam and ...</i></label><input type="text" size="20" name="captcha" maxlength="3"></input>*</p>
                <p class="submit"><input type="submit" value="Submit"></input></p>
                <p class="footline">* = required field</p>
            </fieldset>
        </form>
    <?

    
// fetch guestbook messages from database
    
$result database_transaction("SELECT id, time, name, homepage, email, message FROM guestbook_entries ORDER BY id DESC");

    
// display the messages
    
while ($results mysql_fetch_array($result))
    {
        
$results["time"] = date("H:i j-n-Y",$results["time"]);
            
?><p class="message<? echo $alternate%2?>"><?
        
// if no homepage and email are entered
        
if($results["homepage"]==""&&$results["email"]=="")
            
printf("On %s %s wrote<br />%s"$results["time"], $results["name"], $results["message"]);
        
// if only homepage is entered
        
else if($results["email"]=="")
            
printf("On %s %s (<a href='%s'>link</a>) wrote<br />%s"$results["time"], $results["name"], $results["homepage"], $results["message"]);
        
// if only email is entered
        
else if($results["homepage"]=="")
            
printf("On %s <a href='mailto:%s'>%s</a> wrote<br />%s"$results["time"], $results["email"], $results["name"], $results["message"]);
        
// if homepage and email are entered
        
else
            
printf("On %s <a href='mailto:%s'>%s</a> (<a href='%s'>link</a>) wrote<br />%s"$results["time"], $results["email"], $results["name"], $results["homepage"], $results["message"]);
            echo 
"</p>";
        
$alternate++;
    }

    
?>
    
            <p class="footline"><br />Guestbookscript v0.4 by <a href="http://mathijs.info">Mathijs</a> - view <a href="../files/junk/guestbook.phps">source</a></p>
       </div>
    <?
}
?>