<?

# Ben's Journal Code v.05 - php/mysql journal - December 27, 2002
# Copyright 2002 Ben Livingston <ben at oblivion dot net>
# Released under the GNU General Public License Version 2
# Viewable online at http://www.gnu.org/copyleft/gpl.html

/* MySQL dump

CREATE TABLE journal (
   id int(10) unsigned NOT NULL auto_increment,
   date date DEFAULT '0000-00-00' NOT NULL,
   title varchar(255) NOT NULL,
   text mediumtext NOT NULL,
   PRIMARY KEY (id)
);

CREATE TABLE journal_comment (
   id int(10) unsigned NOT NULL,
   entry int(10) unsigned NOT NULL,
   user int(10) unsigned NOT NULL,
   comment mediumtext NOT NULL,
   PRIMARY KEY (id),
   KEY entry (entry)
);

CREATE TABLE users (
   id tinyint(3) unsigned NOT NULL auto_increment,
   handle varchar(32) NOT NULL,
   password varchar(16) NOT NULL,
   email varchar(255) NOT NULL,
   score smallint(3) unsigned NOT NULL,
   PRIMARY KEY (id)
);

*/

# # # # # # # # #
# Configuration #
# # # # # # # # #

define('DB_HOST','localhost');
define('DB_USER','define this');
define('DB_PASS','define this');
define('DB_DATABASE','journal');
define('ADMIN_EMAIL','you@localhost');
# Cookie configuration
define('COOKIE_USER','RandomKeyPunchingsUser');
define('COOKIE_PASS','RandomKeyPunchingsUser');
define('COOKIE_DOMAIN','oblivion.net');
define('COOKIE_PATH','/~ben/');
# Include a header and/or footer file
#define('INCLUDE_HEADER','');
#define('INCLUDE_FOOTER','');
# Use a graphic for the submit button in the little_box function. (I use a blank graphic.)
#define('BUTTON_GO','/~ben/images/blank.gif');

# You shouldn't need to edit anything below here, but quite honestly,
# this isn't the best code so you may want to anyway.

if (isset($_REQUEST['comment'])) $comment $_REQUEST['comment'];
if (isset(
$_REQUEST['handle'])) $handle $_REQUEST['handle'];
if (isset(
$_REQUEST['password'])) $password $_REQUEST['password'];
if (isset(
$_REQUEST['text'])) $text $_REQUEST['text'];

function 
set_cookie ($handle,$password) {
  
$pass mysql_query("SELECT PASSWORD('$password')");
  
setcookie(COOKIE_USER,$handle,time()+31536000,COOKIE_PATH,'.'.COOKIE_DOMAIN);
  
setcookie(COOKIE_PASS,mysql_result($pass,0),time()+31536000,COOKIE_PATH,'.'.COOKIE_DOMAIN);
}

function 
register ($handle,$password,$verify,$email,$setcookie='') {
    if(
$password != $verify)
        echo 
"You messed up on your password. Go back and try again.";
    else {
        
$result mysql_query("SELECT * FROM users WHERE handle='$handle'");
        if (
mysql_num_rows($result))
            echo 
"Handle <u>$handle</u> already exists. Please go back and choose another handle.";
        else {
            
$result mysql_query("SELECT * FROM users WHERE email='$email'");
            if (
mysql_num_rows($result))
                echo 
"Email address <u>$email</u>already exists in database.";
            else {
                
mysql_query("INSERT INTO users (id, handle, password, email) VALUES ('', '$handle', PASSWORD('$password'), '$email')")
                    or die(
mysql_error());
                echo 
"You have been assigned the handle <u>$handle</u>. Your email address is $email. Thank you for registering.";
                
mail(ADMIN_EMAIL"user registration""$handle has been registerd to $email.\n");
            }
        }
    }
}
    
function 
display_register () {
?>
All of the fields below are required.
<form method="post" action="<? echo $_SERVER['PHP_SELF'?>?register=1">
<table>
<tr><td align="right"><font face="Verdana, Arial" ID="plain">handle:</font></td><td><input name="handle"></td></tr>
<tr><td align="right"><font face="Verdana, Arial" ID="plain">password:</font></td><td><input type="password" name="password"></td></tr>
<tr><td align="right"><font face="Verdana, Arial" ID="plain">verify password:</font></td><td><input type="password" name="verify"></td></tr>
<tr><td align="right"><font face="Verdana, Arial" ID="plain">email:</font></td><td><input name="email"></td></tr>
<tr><td></td><td><font face="Verdana, Arial" ID="plain"><input type="checkbox" name="setcookie" value="1"<? if (!empty($_REQUEST['setcookie'])) { echo " CHECKED"; } ?>>Set me a cookie, yo.</font></td></tr>
</table>
<a href="<? echo $_SERVER['PHP_SELF'?>?register=1">Register</a><br>
<center><input type="submit" name="submit" value="register"></center>
<?
}

function 
email_pass () {
  global 
$handle;
  if (!(
$handle) && ($_COOKIE[COOKIE_USER])) $handle $_COOKIE[COOKIE_USER];
  
$result mysql_query("SELECT email,password FROM users WHERE handle='$handle'");
  if (
mysql_num_rows($result)) {
    
$row mysql_fetch_object($result);
    
mail("$row->email""r.k.p. password""Hi, this is Ben's web site, over at http://oblivion.net/~ben. Your\npassword is '$row->password' -- minus the quotes.\n\n");
    echo 
"I've sent email to the contact address for this web site. If this is you, check your email.";
  }
}

function 
entry_list($start) {        // Unfinished
  
if (!$start)
    
$start 0;
  
$result mysql_query("SELECT *,source.name as source,LEFT(text,LOCATE('\n',text)) as text,article.id as id,DATE_formAT(date, '%M %e, %Y') as date FROM article,source where source.id=article.source ORDER BY article.id DESC LIMIT $start,20;");
  if (!
mysql_num_rows($result))
    echo 
"No news!";
  else {
    echo 
"<p align=\"right\"><a href=\"" $_SERVER['PHP_SELF'] . "?start=" . ($start+20) . '">last 20 articles</a></p>';
    while (
$row mysql_fetch_object($result)) {
      echo 
"<a href=\"" $_SERVER['PHP_SELF'] . "?article=$row->id\">" stripslashes($row->title) . "</a><br>\n<font size=\"-1\">$row->source, $row->date - Posted " date("F j"$row->id) . "</font>\n<p>" stripslashes($row->text) . "</p>\n\n";
    }
  }
}

function 
get_high_entry() {
  
$result mysql_query("SELECT id FROM journal ORDER BY id DESC LIMIT 1")
    or die(
"1Bad query: ".mysql_error());
  if (
mysql_num_rows($result))
    return 
mysql_result($result,0,'id');
}


function 
little_box($entry) {
  global 
$high_entry;
?>
<form method="GET" action="<? echo $_SERVER['PHP_SELF'?>">
<center><table cellpadding="1" cellspacing="0" border="0" width="100%">
<tr><td bgcolor="#000000">
<table cellpadding="0" cellspacing="0" border="0" width="100%">
<tr><td bgcolor="#FFFFFF" width="50%" align="center">
<font face="Arial" SIZE="-1">
<? if ($entry 1) { echo "&nbsp;<a href=\"" $_SERVER['PHP_SELF'] . "?entry="$entry-1"\"><font color=\"#000000\">&lt;&lt;</font></a>"; } ?>
&nbsp;<input type="text" name="entry" size="3" MAXLENGTH="3"><?
  
if (defined("BUTTON_GO")) echo '<input type="image" src="' BUTTON_GO '" alt="go!" border="0">';
  else echo 
"<input type=\"submit\" value=\"go\">";
  if (
$entry $high_entry) { echo "<a href=\"" $_SERVER['PHP_SELF'] . "?entry="$entry+1"\"><font color=\"#000000\">&gt;&gt;</font></a>&nbsp;"; } ?>
</td><td bgcolor="#FFFFFF" width="50%" align="center">
<font face="Arial" SIZE="-1">
<font color="#000000">&nbsp;valid numbers: <a href="<? echo $_SERVER['PHP_SELF'?>?entry=1"><font color="#000000">1</font></a> &#0150; <a href="<? echo $_SERVER['PHP_SELF'] . "?entry=$high_entry"?>"><font color="#000000"><? echo $high_entry ?></font></a>&nbsp;</font>
</font>
</td></tr></table>
</td></tr></table>
</center>
</form>

<?
}

function 
entry($id) {
  if (
$id) {
    
$result mysql_query("SELECT *, DATE_formAT(date, '%W, %M %e, %Y') as date FROM journal WHERE id=$id")
      or die(
"2Bad query: ".mysql_error());
  }
  else {
    
$result mysql_query("SELECT *, DATE_formAT(date, '%W, %M %e, %Y') as date FROM journal ORDER BY id DESC LIMIT 1")
      or die(
"3Bad query: ".mysql_error());
  }
  if (!
mysql_num_rows($result)) {
    echo 
"No such entry";
  }
  else {
    
little_box($id);
    
$row mysql_fetch_object($result);
    
$GLOBALS['entry']=$row->id;
    if (
$row->title)
      echo 
"<h1 id=\"head\">" stripslashes($row->title) . "</h1>\n\n";
    echo 
"<p>Entry #$row->id<br>\n<b>$row->date</b></p>\n\n";
    
$row->text eregi_replace("(\r|\n)+","</p>\n<p>",$row->text);
    
$row->text eregi_replace("</p>\n<p>(</?(UL|OL|DL|LI|DD|DT)>|$)","\n\\1",$row->text);
    
$row->text stripslashes($row->text);
    echo 
"<p>$row->text\n\n";
    echo 
"<p><a href=\"" $_SERVER['PHP_SELF'] . "?comment=$row->id\">Comment on this entry</a></p>";
  }
}

function 
comment($id) {
  
$result mysql_query("SELECT journal_comment.*,users.handle FROM journal_comment,users WHERE journal_comment.entry=$id AND users.id=journal_comment.user ORDER BY id")
    or die(
"4Bad query: ".mysql_error());
  while (
$row mysql_fetch_object($result)) {
    
$row->handle ereg_replace("<([^>]*)>","&lt;\\1&gt;",$row->handle);
    echo 
"<hr size=\"1\"><b>From: $row->handle<br>" date("D M d, Y @ g:i a",$row->id) . "</b><br><br>\n\n";
    
$row->comment stripslashes($row->comment);
    
$row->comment ereg_replace("<([^>]*)>","&lt;\\1&gt;",$row->comment);
    
$row->comment ereg_replace("\n+","</p>\n\n<p>",$row->comment);
    echo 
"<p>$row->comment</p>";
  }
}

function 
comment_form($comment$handle=''$text='',$setcookie='') {
  global 
$comment$handle$text$setcookie;
?>
<form action="<? echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="hidden" name="comment" value="<? echo $comment ?>">
<textarea name="text" rows="8" cols="35" no wrap><? if ($text) echo stripslashes($text); else echo "Hit enter twice to start a new paragraph (remove this text)."?></textarea><br>
<? if ($_COOKIE[COOKIE_USER]) echo "If you are " $_COOKIE[COOKIE_USER] . ", everything below is optional.<br>"?>
handle: <input type="text" size="8" name="handle"<? if ($handle) echo " value=\"$handle\""?>">
 &nbsp; pass: <input type="password" SIZE="8" name="password"><br>
<input type="checkbox" name="setcookie" value="1"<? if (!empty($_REQUEST['setcookie'])) { echo " checked"; } ?>>Remember me, yo.<br>
<a href="<? echo $_SERVER['PHP_SELF'?>?register=1">Register</a><br>
<center><input type="submit" name="submit" value="submit"></center>
</form>
<?
/* Use <a href="/~ben/feedback.cgi">this form</a> to send me email without posting to my page. */
}

function 
comment_submit() {
  global 
$comment$handle$password$text$high_entry;
  
$id time();
  if (
$handle) {
    
$result mysql_query("SELECT * FROM users WHERE handle='$handle'")
      or die(
"5Bad query: ".mysql_error());
  }
  else {
    
$result mysql_query("SELECT * FROM users WHERE handle='" $_COOKIE[COOKIE_USER] . "'")
      or die(
"6Bad query: ".mysql_error());
  }
  if (!
mysql_num_rows($result)) {
    echo 
"Invalid username: '$handle'. Need to <a href=\"" $_SERVER['PHP_SELF'] . "?register=1\">register</a>?<br><br>";
    
comment_form($comment);
  }
  else {
    
$user mysql_fetch_object($result);
    if (
$password) {
      
$pass mysql_query("SELECT PASSWORD('$password')");
      
$_COOKIE[COOKIE_PASS] = mysql_result($pass,0);
    }
    if (
$_COOKIE[COOKIE_PASS] != $user->password) {
      echo 
"Username and password don't match.</p>";
      
comment_form($comment);
    }
    else {
      if ((empty(
$comment)) or ($comment 0) or ($comment $high_entry)) {
        echo 
"You can't comment on a non-existant entry.";
      }
      else {
        
$result mysql_query("INSERT INTO journal_comment (id,entry,user,comment) VALUES('$id', '$comment','$user->id','" $text "')")
          or die(
"7Bad query: ".mysql_error());
        echo 
"Thanks for your comment. <a href=\"" $_SERVER['PHP_SELF'] . "\">Click here</a> to see it.";
        
mail(ADMIN_EMAIL"comment""$user->handle has commented on entry #$comment.\n\n$text");
      }
    }
  }
}

// main code
// set cookie before outputting any headers
if (isset($_REQUEST['setcookie']) && isset($_REQUEST['handle']) && isset($_REQUEST['password']))
  
set_cookie($_REQUEST['handle'],$_REQUEST['password']);
// include header
if (defined("INCLUDE_HEADER")) include(INCLUDE_HEADER);
// connect to mysql database
$link mysql_connect(DB_HOST,DB_USER,DB_PASS) or die("Can't connect to MySQL database.<br>\n" mysql_error());
$foo mysql_select_db(DB_DATABASE,$link) or die("test" mysql_error());
// get the journal entry with the highest id number
$high_entry get_high_entry();
// if user sends entry variable, use that
if (!empty($_REQUEST['entry']))
  
$entry=$_REQUEST['entry'];
// else use $high_entry
else
  
$entry=$high_entry;

// display list of entries
if (isset($_REQUEST['list']))
  
entry_list($_REQUEST['start']);
// email password
#elseif (($submit) && ((!$password) && (!$cookie_pass)))
#  email_pass();
// submit comment
elseif (isset($_REQUEST['comment'], $_REQUEST['submit']))
  
comment_submit();
// display comment form
elseif (isset($_REQUEST['comment']))
  
comment_form($_REQUEST['comment']);
// user registration
elseif (isset($_REQUEST['register'], $_REQUEST['submit'])) {
  
// make sure all required variables are filled
  
if (!empty($_REQUEST['handle']) && !empty($_REQUEST['password']) && !empty($_REQUEST['verify']) && !empty($_REQUEST['email'])) {
    
// check if they want to set a cookie
    
if (!empty($_REQUEST['setcookie']))
      
register($_REQUEST['handle'],$_REQUEST['password'],$_REQUEST['verify'],$_REQUEST['email'],$_REQUEST['setcookie']);
    else
      
register($_REQUEST['handle'],$_REQUEST['password'],$_REQUEST['verify'],$_REQUEST['email']);
  }
  
// display error if they didn't fill in all fields
  
else {
    echo 
"You didn't fill in all of the fields. Try again. ";
    
display_register();
  }
}
// display user registration form
elseif (isset($_REQUEST['register']))
    
display_register();
// display an entry and any comments
else {
  
entry($entry);
  
comment($entry);
}
// close the mysql connection
mysql_close($link);

// include the footer
if (defined("INCLUDE_FOOTER")) include(INCLUDE_FOOTER);

?>