Skip navigation

Beginning PHP, Apache, MySQL Web Development

Chapter 15 Code - Creating a Bulletin Board System

Try It Out 1

conn.php - Try It Out 1

<?php
define('SQL_HOST','localhost');
define('SQL_USER','buzzly_comic');
define('SQL_PASS','spiderman');
define('SQL_DB','buzzly_comicsite');

$conn = mysql_connect(SQL_HOST,SQL_USER,SQL_PASS)
  or die('Could not connect to the database; ' . mysql_error());

mysql_select_db(SQL_DB,$conn)
  or die('Could not select database; ' . mysql_error());
?>

setup.php - Try It Out 1

<?php
require_once "conn.php";
$adminemail = "admin@yoursite.com";
$adminpass = "admin";
$adminname = "Admin";

/******* Access Levels Table *****************************************/
$sql = <<<EOS
CREATE TABLE forum_access_levels (
  access_lvl tinyint(4) NOT NULL auto_increment,
  access_name varchar(50) NOT NULL default '',
  PRIMARY KEY (access_lvl)
)
EOS;
$result = mysql_query($sql);
switch(mysql_errno()) {
  case 1050:
    break;
  case 0:
    $sql = "INSERT IGNORE INTO forum_access_levels
      VALUES (1,'User')";
    $result = mysql_query($sql) or die(mysql_error());
    $sql = "INSERT IGNORE INTO forum_access_levels
      VALUES (2,'Moderator')";
    $result = mysql_query($sql) or die(mysql_error());
    $sql = "INSERT IGNORE INTO forum_access_levels
      VALUES (3,'Administrator')";
    $result = mysql_query($sql) or die(mysql_error());
    break;
  default:
    die(mysql_error());
    break;
}
$a_tables[] = "forum_access_levels";

/******* Admin Table *************************************************/
$sql = <<<EOS
CREATE TABLE  forum_admin (
  id int(11) NOT NULL auto_increment,
  title varchar(100) NOT NULL default '',
  value varchar(255) NOT NULL default '',
  constant varchar(100) NOT NULL default '',
  PRIMARY KEY  (id)
)
EOS;
$result = mysql_query($sql);
switch(mysql_errno()) {
  case 1050:
    break;
  case 0:
    $sql = "INSERT INTO forum_admin VALUES (NULL,
      'Board Title', 'Comic Book Appreciation Forums', 'title')";
    $result = mysql_query($sql) or die(mysql_error());
    $sql = "INSERT INTO forum_admin VALUES (NULL, ".
           "'Board Description', 'The place to discuss your favorite ".
           "comic books, movies, and more!', 'description')";
    $result = mysql_query($sql) or die(mysql_error());
    $sql = "INSERT INTO forum_admin VALUES (NULL, ".
           "'Admin Email', '$adminemail', 'admin_email')";
    $result = mysql_query($sql) or die(mysql_error());
    $sql = "INSERT INTO forum_admin VALUES (NULL, 'Copyright', ".
           "'© 2003 CBA Inc.  All rights reserved.', ".
           "'copyright')";

    $result = mysql_query($sql) or die(mysql_error());
    $sql = "INSERT INTO forum_admin VALUES (NULL, ".
           "'Board Titlebar', 'CBA Forums', 'titlebar')";
    $result = mysql_query($sql) or die(mysql_error());
    $sql = "INSERT INTO forum_admin VALUES (NULL, ".
           "'Pagination Limit', '10', 'pageLimit')";
    $result = mysql_query($sql) or die(mysql_error());
    $sql = "INSERT INTO forum_admin VALUES (NULL, ".
           "'Pagination Range', '7', 'pageRange')";
    $result = mysql_query($sql) or die(mysql_error());
    break;
  default:
    die(mysql_error());
    break;
}
$a_tables[] = "forum_admin";

/******* BBcode Table ************************************************/
$sql = <<<EOS
CREATE TABLE IF NOT EXISTS forum_bbcode (
  id int(11) NOT NULL auto_increment,
  template varchar(255) NOT NULL default '',
  replacement varchar(255) NOT NULL default '',
  PRIMARY KEY  (id)
)
EOS;
$result = mysql_query($sql) or die(mysql_error());
$a_tables[] = "forum_bbcode";

/******* Forum Table *************************************************/
$sql = <<<EOS
CREATE TABLE  forum_forum (
  id int(11) NOT NULL auto_increment,
  forum_name varchar(100) NOT NULL default '',
  forum_desc varchar(255) NOT NULL default '',
  forum_moderator int(11) NOT NULL default '0',
  PRIMARY KEY  (id)
)
EOS;
$result = mysql_query($sql);
switch(mysql_errno()) {
  case 1050:
    break;
  case 0:
    $sql = "INSERT INTO forum_forum VALUES (NULL, 'New Forum', ".
           "'This is the initial forum created when installing the ".
           "database.  Change the name and the description after ".
           "installation.', 1)";
    $result = mysql_query($sql) or die(mysql_error());
    break;
  default:
    die(mysql_error());
    break;
}
$a_tables[] = "forum_forum";

/******* Post Count Table ********************************************/
$sql = <<<EOS
CREATE TABLE forum_postcount (
  user_id int(11) NOT NULL default '0',
  count int(9) NOT NULL default '0',
  PRIMARY KEY  (user_id)
)
EOS;
$result = mysql_query($sql);
switch(mysql_errno()) {
  case 1050:
    break;
  case 0:
    $sql = "INSERT INTO forum_postcount VALUES (1,1)";
    $result = mysql_query($sql) or die(mysql_error());
    break;
  default:
    die(mysql_error());
    break;
}
$a_tables[] = "forum_postcount";

/******* Posts Table *************************************************/
$sql = <<<EOS
CREATE TABLE  forum_posts (
  id int(11) NOT NULL auto_increment,
  topic_id int(11) NOT NULL default '0',
  forum_id int(11) NOT NULL default '0',
  author_id int(11) NOT NULL default '0',
  update_id int(11) NOT NULL default '0',
  date_posted datetime NOT NULL default '0000-00-00 00:00:00',
  date_updated datetime NOT NULL default '0000-00-00 00:00:00',
  subject varchar(255) NOT NULL default '',
  body mediumtext NOT NULL,
  PRIMARY KEY  (id),
  KEY IdxArticle (forum_id,topic_id,author_id,date_posted),
  FULLTEXT KEY IdxText (subject,body)
)
EOS;
$result = mysql_query($sql);
switch(mysql_errno()) {
  case 1050:
    break;
  case 0:
    $sql = "INSERT INTO forum_posts VALUES (NULL, 0, 1, 1, 0, '".
    date("Y-m-d H:i:s", time())."', 0, 'Welcome', 'Welcome to your ".
    "new Bulletin Board System. Do not forget to change your admin ".
    "password after installation. Have fun!')";
    $result = mysql_query($sql) or die(mysql_error());
    break;
  default:
    die(mysql_error());
    break;
}
$a_tables[] = "forum_posts";

/******* Users Table *************************************************/
$sql = <<<EOS
CREATE TABLE  forum_users (
  id int(11) NOT NULL auto_increment,
  email varchar(255) NOT NULL default '',
  passwd varchar(50) NOT NULL default '',
  name varchar(100) NOT NULL default '',
  access_lvl tinyint(4) NOT NULL default '1',
  signature varchar(255) NOT NULL default '',
  date_joined datetime NOT NULL default '0000-00-00 00:00:00',
  last_login datetime NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY  (id),
  UNIQUE KEY uniq_email (email)
)
EOS;
$result = mysql_query($sql);
switch(mysql_errno()) {
  case 1050:
    break;
  case 0:
    $datetime = date("Y-m-d H:i:s",time());
    $sql = "INSERT IGNORE INTO forum_users VALUES (NULL, ".
           "'$adminemail', '$adminpass', '$adminname', 3, '', ".
           "'$datetime', 0)";
    $result = mysql_query($sql) or die(mysql_error());
    break;
  default:
    die(mysql_error());
    break;
}
$a_tables[] = "forum_users";

/******* Display Results *********************************************/
require("config.php");
echo "<html><head><title>Forum Tables Created " .
     $datetime . "</title>";
echo "<link rel='stylesheet' type='text/css' ";
echo "href='forum_styles.css'>";
echo "</head><body>";
echo "<div class='bodysmall'>";
echo "<h1>".$admin['title']['value']."</h1>";
echo "<H3>Forum Tables created:</h3>\n<ul>";
foreach ($a_tables as $table) {
  $table = str_replace("forum_","",$table);
  $table = str_replace("_", " ",$table);
  $table = ucWords($table);
  echo "<li>$table</li>\n";
}
echo "</ul>\n<h3>Here is your initial login information:</h3>\n";
echo "<ul><li><strong>login</strong>: " . $adminemail . "</li>\n";
echo "<li><strong>password</strong>: " . $adminpass . "</li></ul>\n";
echo "<h3><a href='login.php?e=".$adminemail."'>Log In</a> ";
echo "to the site now.</h3></div>";
echo "<div class='copyright'>".$admin['copyright']['value']."</div>";
echo "</body></html>";
?>

functions.php - Try It Out 1

<?php
function trimBody($theText, $lmt=100, $s_chr="@@@", $s_cnt=1) {
  $pos = 0;
  $trimmed = FALSE;
  for ($i = 1; $i <= $s_cnt; $i++) {
    if ($tmp = strpos($theText,$s_chr,$pos)) {
      $pos = $tmp;
      $trimmed = TRUE;
    } else {
      $pos = strlen($theText);
      $trimmed = FALSE;
      break;
    }
  }
  $theText = substr($theText,0,$pos);

  if (strlen($theText) > $lmt) {
    $theText = substr($theText,0,$lmt);
    $theText = substr($theText,0,strrpos($theText,' '));
    $trimmed = TRUE;
  }
  if ($trimmed) $theText .= '...';
  return $theText;
}

function msgBox($m, $t, $d="index.php", $s="Info") {
  $theMsg = "<div id='requestConfirm" . $s . "'>";
  $theMsg .= "<h2>" . $t . "</h2>\n";
  $theMsg .= "<p>" . $m . "</p>";
  $theMsg .= "<p><a href='" . $d . "' ";
  $theMsg .= "class='buttonlink'>";
  $theMsg .= "Yes</a>";
  $theMsg .= "<a href='index.php' class='buttonlink'>";
  $theMsg .= "No</a></p>";
  $theMsg .= "</div>";
  return $theMsg;
}

function getForum($id) {
  $sql = "SELECT forum_name as name, forum_desc as description, ".
           "forum_moderator as mod ".
         "FROM forum_forum ".
         "WHERE id = " . $id;
  $result = mysql_query($sql)
    or die(mysql_error() . "<br>" . $sql);
  $row = mysql_fetch_array($result);
  return $row;
}

function getForumID($topicid) {
  $sql = "SELECT forum_id FROM forum_posts WHERE id=$topicid";
  $result = mysql_query($sql)
    or die(mysql_error() . "<br>" . $sql);
  $row = mysql_fetch_array($result);
  return $row['forum_id'];
}

function breadcrumb($id, $getfrom="F") {
  $sep = "<span class='bcsep'>";
  $sep .= " &middot; ";

  $sep .= "</span>";
  if ($getfrom == "P") {
    $sql = "SELECT forum_id, subject FROM forum_posts ".
           "WHERE id = " . $id;
    $result = mysql_query($sql)
      or die(mysql_error() . "<br>" . $sql);
    $row = mysql_fetch_array($result);
    $id = $row['forum_id'];
    $topic = $row['subject'];
  }
  $row = getForum($id);
  $bc = "<a href='index.php'>Home</a>$sep";
  switch ($getfrom) {
    case "P":
      $bc .= "<a href='viewforum.php?f=$id'>".$row['name'].
            "</a>$sep".$topic;
      break;
    case "F":
      $bc .= $row['name'];
      break;
    default:
  }
 return "<h4 class='breadcrumb'>" . $bc . "</h4>";
}

function showTopic($topicid, $showfull=TRUE) {
  global $conn;
  global $userid;
  global $limit;

  echo breadcrumb($topicid, "P");
  if (isset($_GET['page'])) {
    $page = $_GET['page'];
  } else {
    $page = 1;
  }
  if ($limit == "") $limit = 25;
  $start = ($page - 1) * $limit;
  if (isset($_SESSION['user_id'])) {
    echo topicReplyBar($topicid, getForumID($topicid), "right");
  }
  $sql = "SELECT SQL_CALC_FOUND_ROWS ".
           "p.id, p.subject, p.body, p.date_posted, " .
           "p.date_updated, u.name as author, u.id as author_id, " .
           "u.signature as sig, c.count as postcount, " .
           "p.forum_id as forum_id, f.forum_moderator as mod, " .
           "p.update_id, u2.name as updated_by " .
         "FROM forum_forum f " .
         "JOIN forum_posts p " .
         "ON f.id = p.forum_id " .
         "JOIN forum_users u " .
         "ON u.id = p.author_id " .
         "LEFT JOIN forum_users u2 " .
         "ON u2.id = p.update_id " .
         "LEFT JOIN forum_postcount c " .
         "ON u.id = c.user_id " .
         "WHERE (p.topic_id = $topicid OR p.id = $topicid) " .
         "ORDER BY p.topic_id, p.date_posted ".
         "LIMIT $start,$limit";
  $result = mysql_query($sql,$conn)
    or die(mysql_error() . "<br>" . $sql);
  $pagelinks = paginate($limit);
  if (mysql_num_rows($result) == 0) {
    $msg = "There are currently no posts.  Would you " .
           "like to be the first person to create a thread?";
    $title = "No Posts...";
    $dest = "compose.php?forumid=" . $forumid;
    $sev = "Info";
    $message = msgBox($msg,$title,$dest,$sev);
    echo $message;
   } else {
    echo "<table class='forumtable' cellspacing='0' ";
    echo "cellpadding='2'><tr>";
    echo "<th class='author'>Author</th>";
    echo "<th class='post'>Post</th>";
    echo "</tr>";
    while ($row = mysql_fetch_array($result)) {
      $lastupdate = "";
      $editlink = "";
      $dellink = "";
      $replylink = "&nbsp;";
      $pcount = "";
      $pdate = "";
      $sig = "";
      if ($showfull) {
        $body = $row['body'];
        if (isset($_SESSION['user_id'])) {
          $replylink = "<a href='compose.php?forumid=".
            $row['forum_id']."&topicid=$topicid&reid=".$row['id'].
            "' class='buttonlink'>REPLY</a>&nbsp;";
        } else {
          $replylink = "";
        }
        if ($row['update_id'] > 0) {
        $lastupdate = "<p class='smallNote'>Last updated: " .
             $row['date_updated'] . " by " .
             $row['updated_by'] . "</p>";
        }
        if (($userid == $row['author_id']) or
            ($userid == $row['mod']) or
            ($_SESSION['access_lvl'] > 2)) {
          $editlink = "<a href='compose.php?a=edit&post=".$row['id'].
            "' class='buttonlink'>EDIT</a>&nbsp;";
          $dellink = "<a href='transact-affirm.php?action=deletepost&".
            "id=" . $row['id'] .
            "' class='buttonlink'>DELETE</a>&nbsp;";
        }
        $pcount = "<br /><span class='textsmall'>Posts: " .
          ($row['postcount']==""?"0":$row['postcount']) . "</span>";
        $pdate = $row['date_posted'];
        $sig = ($row['sig'] != ""?"<p class='sig'>".
               bbcode(nl2br($row['sig'])):"")."</p>";
      } else {
        $body = trimBody($body);
      }
      $rowclass = ($rowclass == "row1"?"row2":"row1");
      echo "<tr class='$rowclass'>";
      echo "<td class='author'>" . $row['author'];
      echo $pcount;
      echo "</td><td class='post'><p>";
      if (isset($_SESSION['user_id'])
          and ($_SESSION['last_login'] < $row['date_posted'])) {
        echo NEWPOST . " ";
      }
      if (isset($_GET['page'])) $pagelink = "&page=" . $_GET['page'];
      echo "<a name='post" . $row['id'] .
           "' href='viewtopic.php?t=" . $topicid . $pagelink . "#post" .
           $row['id'] . "'>".POSTLINK."</a>";
      if (isset($row['subject'])) {
        echo " <strong>" . $row['subject'] . "</strong>";
      }
      echo "</p><p>" . bbcode(nl2br(htmlspecialchars($body))) . "</p>";
      echo $sig;
      echo $lastupdate;
      echo "</td></tr>";
      echo "<tr class='$rowclass'><td class='authorfooter'>";
      echo $pdate . "</td><td class='threadfooter'>";
      echo $replylink;
      echo $editlink;
      echo $dellink;
      echo "</td></tr>\n";
    }
    echo "</table>";
    echo $pagelinks;
    echo "<p>".NEWPOST." = New Post&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
    echo POSTLINK." = Post link (use to bookmark)</p>";
  }
}

function isParent($page) {
  $currentpage = $_SERVER['PHP_SELF'];
  if (strpos($currentpage, $page) === false) {
    return FALSE;
  } else {
    return TRUE;
  }
}

function topicReplyBar($topicid,$forumid,$pos="right") {
  $html = "<p class='buttonBar" . $pos . "'>";
  if ($topicid > 0) {
    $html .= "<a href='compose.php?forumid=$forumid".
       "&topicid=$topicid&reid=$topicid' class='buttonlink'>Reply ".
       "to Thread</a>";
  }
  if ($forumid > 0) {
    $html .= "<a href='compose.php?forumid=$forumid' ".
       "class='buttonlink'>New Thread</a>";
  }
  $html .= "</p>";
  return $html;
}

function userOptionList($level) {
  $sql = "SELECT id, name, access_lvl " .
         "FROM forum_users " .
         "WHERE access_lvl=" . $level . " " .
         "ORDER BY name";
  $result = mysql_query($sql) or die(mysql_error());

  while ($row = mysql_fetch_array($result)) {
    echo "<option value='". $row['id'] . "'>" .
         htmlspecialchars($row['name']) . "</options>";
  }
}

function paginate($limit=10) {
  global $admin;

  $sql = "SELECT FOUND_ROWS();";
  $result = mysql_query($sql) or die(mysql_error());
  $row = mysql_fetch_array($result);
  $numrows = $row[0];
  $pagelinks = "<div class=pagelinks>";
  if ($numrows > $limit) {
    if(isset($_GET['page'])){
      $page = $_GET['page'];
    } else {
      $page = 1;
    }
    $currpage = $_SERVER['PHP_SELF'] . "?" . $_SERVER['QUERY_STRING'];
    $currpage = str_replace("&page=".$page,"",$currpage);

    if($page == 1){
      $pagelinks .= "<span class='pageprevdead'>&lt; PREV</span>";
    }else{
      $pageprev = $page - 1;
      $pagelinks .= "<a class='pageprevlink' href='" . $currpage .
        "&page=" . $pageprev . "'>&lt; PREV</a>";
    }

    $numofpages = ceil($numrows / $limit);
    $range = $admin['pageRange']['value'];
    if ($range == "" or $range == 0) $range = 7;
    $lrange = max(1,$page-(($range-1)/2));
    $rrange = min($numofpages,$page+(($range-1)/2));
    if (($rrange - $lrange) < ($range - 1)) {
      if ($lrange == 1) {
        $rrange = min($lrange + ($range-1), $numofpages);
      } else {
        $lrange = max($rrange - ($range-1), 0);
      }
    }

    if ($lrange > 1) {
      $pagelinks .= "..";
    } else {
      $pagelinks .= "&nbsp;&nbsp;";
    }
    for($i = 1; $i <= $numofpages; $i++){
      if($i == $page){
        $pagelinks .= "<span class='pagenumdead'>$i</span>";
      }else{
        if ($lrange <= $i and $i <= $rrange) {
          $pagelinks .= "<a class='pagenumlink' href='" . $currpage .
          "&page=" . $i . "'>" . $i . "</a>";
        }
      }
    }
    if ($rrange < $numofpages) {
      $pagelinks .= "..";
    } else {
      $pagelinks .= "&nbsp;&nbsp;";
    }

    if(($numrows - ($limit * $page)) > 0){
      $pagenext = $page + 1;
      $pagelinks .= "<a class='pagenextlink' href='" . $currpage .
        "&page=" . $pagenext . "'>NEXT &gt;</a>";
    } else {
      $pagelinks .= "<span class='pagenextdead'>NEXT &gt;</span>";
    }
  } else {
    $pagelinks .= "<span class='pageprevdead'>
      &lt; PREV</span>&nbsp;&nbsp;";
    $pagelinks .= "<span class='pagenextdead'>
      NEXT &gt;</span>&nbsp;&nbsp;";
  }
  $pagelinks .= "</div>";
  return $pagelinks;
}

function bbcode($data) {
  $sql = "SELECT * FROM forum_bbcode";
  $result = mysql_query($sql);
  if (mysql_num_rows($result) > 0) {
    while($row = mysql_fetch_array($result)) {
      $bbcode['tpl'][] =
        "§" . html_entity_decode($row['template'],ENT_QUOTES). "§i";
      $bbcode['rep'][] =
        html_entity_decode($row['replacement'],ENT_QUOTES);
    }
    $data1 = preg_replace($bbcode['tpl'],$bbcode['rep'],$data);
    $count = 1;
    while (($data1 != $data) and ($count < 4)) {
      $count++;
      $data = $data1;
      $data1 = preg_replace($bbcode['tpl'],$bbcode['rep'],$data);
    }
  }

  return $data;
}
?>

http.php - Try It Out 1

<?php
function redirect($url) {
  if (!headers_sent()) {
    header('Location: http://' . $_SERVER['HTTP_HOST'] .
      dirname($_SERVER['PHP_SELF']) . '/' . $url);
  } else {
    die('Could not redirect; Headers already sent (output).');
  }
}
?>

config.php - Try It Out 1

<?php
require_once 'conn.php';
require_once 'functions.php';

$sql = 'SELECT * FROM forum_admin';
$result = mysql_query($sql) or die(mysql_error());

while ($row = mysql_fetch_array($result)) {
  $admin[$row['constant']]['title'] = $row['title'];
  $admin[$row['constant']]['value'] = $row['value'];
}

$sql = 'SELECT * FROM forum_bbcode';
$result = mysql_query($sql) or die(mysql_error());

while ($row = mysql_fetch_array($result)) {
  $bbcode[$row['id']]['template'] = $row['template'];
  $bbcode[$row['id']]['replacement'] = $row['replacement'];
}

// define constants here:
  define("NEWPOST",
         "<span class='newpost'>&raquo;</span>");
  define("POSTLINK",
         "<span class='postlink'>&diams;</span>");
?>

header.php - Try It Out 1

<?php
session_start();
require_once 'config.php';
$title = $admin[titlebar][value];
if ($pageTitle != "") {
  $title .= " :: " . $pageTitle;
}
$userid = $_SESSION['user_id'];
$access_lvl = $_SESSION['access_lvl'];
$username = $_SESSION['name'];
?>
<html>
<head>
<title><?php echo $title; ?></title>
<link rel="stylesheet" type="text/css" href="forum_styles.css">
</head>
<body>
<div class="body">
<div id="header">
  <form method="get" action="search.php" id="searchbar">
    <input id="searchkeywords" type="text" name="keywords"
    <?php
      if (isset($_GET['keywords'])) {
        echo ' value="' . htmlspecialchars($_GET['keywords']) . '" ';
      }
      echo 'onfocus="this.select();" '
    ?>
      />
      <input id="searchbutton" class="submit" type="submit"
      value="Search" />
  </form>
  <h1 id="sitetitle"><?php echo $admin['title']['value'];?></h1>
  <div id="login">
  <?php
    if (isset($_SESSION['name'])) {
      echo 'Welcome, '.$_SESSION['name'];
    }
  ?>
  </div>
  <p id="subtitle"><?php echo $admin['description']['value']; ?></p>
</div>
<div id="subheader">
  <div id='navigation'>
  <?php
  echo '    <a href="index.php">Home</a>';
  if (!isset($_SESSION['user_id'])) {
    echo ' | <a href="login.php">Log In</a>';
    echo ' | <a href="useraccount.php">Register</a>';
  } else {
    echo ' | <a href="transact-user.php?action=Logout">';
    echo "Log out " . $_SESSION['name'] . "</a>";
    if ($_SESSION['access_lvl'] > 2) {
      echo ' | <a href="admin.php">Admin</a>';
    }
    echo ' | <a href="useraccount.php">Profile</a>';
  }
  ?>
  </div>
</div>

footer.php - Try It Out 1

</div>
<div class="copyright">
  <?php echo $admin[copyright][value]; ?>
</div>
</body>
</html>

index.php - Try It Out 1

<?php
require_once 'conn.php';
require_once 'functions.php';
require_once 'header.php';

$sql = <<<EOS
  SELECT f.id as id, f.forum_name as forum, f.forum_desc as description,
         count(forum_id) as threads, u.name as mod
         FROM forum_forum f
         LEFT JOIN forum_posts p
         ON f.id = p.forum_id
         AND p.topic_id=0
         LEFT JOIN forum_users u
         ON f.forum_moderator = u.id
         GROUP BY f.id
EOS;
$result = mysql_query($sql)
  or die(mysql_error());
if (mysql_num_rows($result) == 0) {
  echo "    <br />\n";
  echo "    There are currently no forums to view.\n";
} else {
  echo "<table class='forumtable' cellspacing='0' ";
  echo "cellspacing='0'><tr>";
  echo "<th class='forum'>Forum</th>";
  echo "<th class='threadcount'>Threads</th>";
  echo "<th class='moderator'>Moderator</th>";
  echo "</tr>";
  while ($row = mysql_fetch_array($result)) {
    $rowclass = ($rowclass == "row1"?"row2":"row1");
    echo "<tr class='$rowclass'>";
    echo "<td class='firstcolumn'><a href='viewforum.php?f=" . $row['id'] . "'>";
    echo $row['forum'] . "</a><br />";
    echo "<span class='forumdesc'>" . $row['description'];
    echo "</span></td>";
    echo "<td class='center'>" . $row['threads'] . "</td>";
    echo "<td class='center'>" . $row['mod'] . "</td>";
    echo "</tr>\n";
  }
  echo "</table>";
}

require_once 'footer.php';
?>

login.php - Try It Out 1

<?php require_once 'header.php';?>
<form name="theForm" method="post" action="transact-user.php">
<h3>Member Login</h3>
<p>
  Email Address:<br />
  <input type="text" name="email" maxlength="255" value="<?php
  echo $_GET['e'];?>" />
</p>
<p>
  Password:<br />
  <input type="password" name="passwd" maxlength="50" />
</p>
<p>
  <input type="submit" class="submit" name="action" value="Login" />
</p>

<p>
  Not a member yet? <a href="useraccount.php">Create a new account!</a>
</p>
<p>
  <a href="forgotpass.php">Forgot your password?</a>
</p>
</form>
<?php require_once 'footer.php'; ?>

forgotpass.php - Try It Out 1

<?php require_once 'header.php'; ?>
<form method="post" action="transact-user.php">
<h3>Email Password Reminder</h3>
<p>
  Forgot your password? Just enter your email address, and we'll email
  your password to you!
</p>
<p>
  Email Address:<br />
  <input type="text" id="email" name="email" />
</p>
<p>
  <input type="submit" class="submit" name="action" value="Send my reminder!" />
</p>
</form>
<?php require_once 'footer.php'; ?>

admin.php - Try It Out 1

<?php
require_once 'header.php';
?>

<script type="text/Javascript">
  <!--
  function delBBCode(id) {
    window.location = "transact-admin.php?action=deleteBBCode&b=" + id;
  }
  function delForum(id) {
    window.location = "transact-affirm.php?action=deleteForum&f=" + id;
}
//-->
</script>

<?php
$sql = "SELECT access_lvl, access_name FROM forum_access_levels " .
       "ORDER by access_lvl DESC";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
  $a_users[$row['access_lvl']] = $row['access_name'];
}

$menuoption = "boardadmin"; // default
if (isset($_GET['option'])) $menuoption = $_GET['option'];

$menuItems = array(
  "boardadmin" => "Board Admin",
  "edituser" => "Users",
  "forums" => "Forums",
  "bbcode" => "BBcode"
  );
echo "<p class='menu'>|";
foreach ($menuItems as $key => $value) {
  if ($menuoption != $key) {
    echo "<a href='" . $_SESSION['PHP_SELF'] . "?option=$key'>";
  }
  echo " $value ";
  if ($menuoption != $key) echo "</a>";
  echo "|";
}
echo "</p>";

switch ($menuoption) {
  case 'boardadmin':
  ?>
    <h3>Board Administration</h3>
    <form id='adminForm' method='post' action='transact-admin.php'>
    <table cellspacing='0' class='forumtable'>
    <tr>
      <th>Title</th><th>Value</th><th>Parameter</th>
    </tr>
  <?php
    foreach ($admin as $k => $v) {
      echo "<tr><td>". $v['title'] . "</td><td>" .
        "<input type='text' name='". $k . "' " .
        "value='" . $v['value'] . "' size='60'>" .
        "</td><td>$k</td></tr>\n";
    }
  ?>
    </table>
    <p class='buttonBar'>
      <input class='submit' type='submit' name="action"
        id="Update" value='Update'>
    </p>
    </form>
  <?php
    break;
  case 'edituser':
  ?>
    <h3>User Administration</h3>
    <div id="users">
    <form name="myform" action="transact-admin.php" method="post">
    Please select a user to admin:<br>
    <select id='userlist' name='userlist[]'>
  <?php
      foreach ($a_users as $key => $value) {
        echo "<optgroup label='". $value . "'>\n";
        userOptionList($key);
        echo "\n</optgroup>\n";
      }
  ?>
    </select>
    <input class="submit"  type="submit" name="action"
            value="Modify User">
    </form>
    </div>
  <?php
    break;
  case 'forums':
    ?>
    <h2>Forum Administration</h2>
    <table class='forumtable' cellspacing='0'>
    <tr><th class="forum">Forum</th><th>&nbsp;</th><th>&nbsp;</th></tr>
    <?php
    $sql = "SELECT * FROM forum_forum";
    $result = mysql_query($sql) or die(mysql_error());
    while ($row = mysql_fetch_array($result)) {
      echo "<tr><td><span class='forumname'>" . $row['forum_name'] .
           "</span><br><span class='forumdesc'>" . $row['forum_desc'] .
           "</span></td><td>" . "<a href='editforum.php?forum=" .
           $row['id'] . "'>Edit</a></td><td>" .
           "<a href='#' onclick='delForum(". $row['id'] .
           ");'>" . "Delete</a></td></tr>";
    }
    ?>
    </table>
    <p class='buttonBar'>
      <a href='editforum.php' class='buttonlink'>New Forum</a>
    </p>
   <?php
    break;
  case 'bbcode':
  ?>
    <h3>BBcode Administration</h3>
    <form id='bbcodeForm' method='post' action='transact-admin.php'>
    <table cellspacing='0' class='forumtable'>
    <tr>
      <th class='template'>Template</th>
      <th class='replacement'>Replacement</th>
      <th class='action'>Action</th>
    </tr>
  <?php
    if (isset($bbcode)) {
      foreach ($bbcode as $k => $v) {
        echo "<tr class='row1'><td>" .
          "<input class='mono' type='text' name='bbcode_t". $k . "' " .
          "value='" . $v['template'] . "' size='32'>" .
          "</td><td>" .
          "<input class='mono' type='text' name='bbcode_r". $k . "' " .
          "value='" . $v['replacement'] . "' size='32'>" .
          "</td><td><input type='button' class='submit' " .
          "name='action' id='DelBBCode' value='Delete' " .
          "onclick='delBBCode(".$k.");'>" .
          "</td></tr>\n";
      }
    }
  ?>
    <tr class='row2'><td colspan='3'>&nbsp;</td></tr>
    <tr class='row2'><td>
    <input class='mono' type='text' name='bbcode-tnew' size='32'>
    </td><td>
    <input class='mono' type='text' name='bbcode-rnew' size='32'>
    </td><td>
    <input type='submit' class='submit' name='action'
      id='AddBBCode' value='Add New'>
    </td></tr>
    </table>
    <p class='buttonBar'>
      <input class='submit' type='submit' name="action"
        id="Update" value='Update BBCodes'>
    </p>
    </form>
  <?php
    break;
  default:
}
?>
</script>
<?php require_once 'footer.php'; ?>

useraccount.php - Try It Out 1

<?php
require_once 'header.php';

$userid = $username = $useremail = $password = $accesslvl = '';
$mode = "Create";
if (isset($_SESSION['user_id'])) {
  $userid = $_SESSION['user_id'];
  $mode = "Edit";
  if (isset($_GET['user'])) {
    if (($_SESSION['user_id'] == $_GET['user'])
        || ($_SESSION['access_lvl'] > 2)) {
      $userid = $_GET['user'];
      $mode = "Modify";
    }
  }
  $sql = "SELECT * FROM forum_users WHERE id=$userid";
  $result = mysql_query($sql)
    or die('Could not look up user data; ' . mysql_error());

  $row = mysql_fetch_array($result);
  $username = $row['name'];
  $useremail = $row['email'];
  $accesslvl = $row['access_lvl'];
  $signature = $row['signature'];
}

echo "<h3>$mode Account</h3>\n";
echo "<form method=\"post\" action=\"transact-user.php\">\n";
?>

<p>
  Full name:<br />
  <input type="text" class="txtinput" name="name" maxlength="100"
    value="<?php echo htmlspecialchars($username); ?>" />
</p>
<?php
  if ($mode == "Edit") {
?>
<p>
  Email Address:<br />
  <input type="text" class="txtinput" name="email" maxlength="255"
    value="<?php echo htmlspecialchars($useremail); ?>" />
</p>
<?php
  }
if ($mode == "Modify") {
  echo "<div><fieldset>\n";
  echo "  <legend>Access Level</legend>\n";

  $sql = "SELECT * FROM forum_access_levels ORDER BY access_lvl DESC";
  $result = mysql_query($sql,$conn)
    or die('Could not list access levels; ' . mysql_error());

  while ($row = mysql_fetch_array($result)) {
    echo '  <input type="radio" class="radio" id="acl_' .
         $row['access_lvl'] . '" name="accesslvl" value="' .
         $row['access_lvl'] . '" ';

    if ($row['access_lvl'] == $accesslvl) {
      echo 'checked="checked" ';
    }
    echo '/>' . $row['access_name'] . "<br />\n";
  }
  echo "</fieldset></div>";
}
if ($mode != "Modify") echo "<div id='passwords'>";
if ($mode == "Edit") {
  if ($_GET['error'] == "nopassedit") {
    echo "<span class='error'>Could not modify passwords.";
    echo " Please try again.</span><br />";
  }
?>
<p>
  Old Password:<br />
  <input type="password" id="oldpasswd"
    name="oldpasswd" maxlength="50" />
</p>
<?php
}
if ($mode != "Modify") {
?>
<p>
  New Password:<br />
  <input type="password" id="passwd" name="passwd" maxlength="50" />
</p>
<p>
  Password Verification:<br />
  <input type="password" id="passwd2" name="passwd2" maxlength="50" />
</p>
<?php }
if ($mode != "Modify") echo "</div>";
if ($mode != "Create") {
?>
<p>
  Signature:<br />
  <textarea name="signature" id="signature" cols=60 rows=5><?php
    echo $signature;?></textarea>
</p>
<?php } ?>
<p>
  <input type="submit" class="submit" name="action"
    value="<?php echo $mode;?> Account" />
</p>
<?php if ($mode == "Edit") {?>
<input type="hidden" name="accesslvl"
  value="<?php echo $accesslvl; ?>" />
<?php } ?>
<input type="hidden" name="userid" value="<?php echo $userid; ?>" />
</form>
<?php require_once 'footer.php'; ?>

editforum.php - Try It Out 1

<?php
if (isset($_GET['forum'])) {
  $action="Edit";
} else {
  $action="Add";
}
$pageTitle = "$action Forum";
require_once 'header.php';

$forum = 0;
$fname = '';
$fdesc = '';
$fmod = '';
$userid = 0;

if (isset($_GET['forum'])) {
  $forum = $_GET['forum'];
  $sql = "SELECT forum_name, forum_desc, u.name, u.id " .
         "FROM forum_forum f " .
         "LEFT JOIN forum_users u " .
         "ON f.forum_moderator = u.id " .
         "WHERE f.id = $forum";
  $result = mysql_query($sql) or die(mysql_error());
  if ($row = mysql_fetch_array($result)) {
    $fname = $row['forum_name'];
    $fdesc = $row['forum_desc'];
    $fmod = $row['name'];
    $userid = $row['id'];
  }
}
echo "<h2>$action forum</h2>";
?>
<form name="forumedit" action="transact-admin.php" method="post">
<table class="forumtable" cellspacing='0'>
<tr><th colspan='2'>General Forum Settings</th></tr>
<tr>
  <td>Forum Name</td>
  <td>
    <input type='text' name='forumname'
      value="<?php echo $fname;?>">
  </td>
</tr>
<tr>
  <td>Forum Description</td>
  <td>
    <input type='text' name='forumdesc' size='75'
      value="<?php echo $fdesc;?>">
  </td>
</tr>
<tr>
  <td>Forum Moderator</td>
  <td>
    <select id="moderator" name="forummod[]">
    <option value='0'>unmoderated</option>
    <?php
    $sql = "SELECT * FROM forum_users ".
           "WHERE access_lvl > 1";
    $result = mysql_query($sql) or die(mysql_error());
    while ($row = mysql_fetch_array($result)) {
      echo "<option value='" . $row['id'] . "'";
      if ($userid == $row['id']) echo " selected='selected'";
      echo ">" . $row['name'] . "</option>";
    }
    ?>
    </select>
  </td>
</tr>
<tr>
  <td colspan='2'>
    <input class="submit" type="submit" name="action"
      value="<?php echo $action;?> Forum">
  </td>
</table>
<input type="hidden" name="forum_id" value="<?php echo $forum;?>">
</form>
<?php require_once 'footer.php';?>

viewtopic.php - Try It Out 1

<?php
require_once 'conn.php';
require_once 'functions.php';
require_once 'http.php';
if (!isset($_GET['t'])) redirect('index.php');
require_once 'header.php';

$topicid = $_GET['t'];
$limit = $admin['pageLimit']['value'];

showTopic($topicid,TRUE);

require_once 'footer.php';
?>

viewforum.php - Try It Out 1

<?php
require_once 'conn.php';
require_once 'functions.php';
require_once 'http.php';
if (!isset($_GET['f'])) redirect('index.php');
require_once 'header.php';

$forumid = $_GET['f'];
$forum = getForum($forumid);

  echo breadcrumb($forumid, "F");
  if (isset($_GET['page'])) {
    $page = $_GET['page'];
  } else {
    $page = 1;
  }
  $limit = $admin['pageLimit']['value'];
  if ($limit == "") $limit = 25;
  $start = ($page - 1) * $admin['pageLimit']['value'];

  $sql = "CREATE TEMPORARY TABLE tmp ( ".
         "topic_id INT(11) NOT NULL DEFAULT 0, ".
         "postdate datetime NOT NULL default '0000-00-00 00:00:00');";
  mysql_query($sql) or die(mysql_error()."<br>".$sql);

  $sql = "LOCK TABLES forum_users READ,forum_posts READ;";
  mysql_query($sql) or die(mysql_error()."<br>".$sql);

  $sql = "INSERT INTO tmp SELECT topic_id,MAX(date_posted) ".
         "FROM forum_posts ".
         "WHERE forum_id = $forumid ".
         "AND topic_id > 0 ".
         "GROUP BY topic_id;";
  mysql_query($sql) or die(mysql_error()."<br>".$sql);

  $sql = "UNLOCK TABLES";
  mysql_query($sql) or die(mysql_error()."<br>".$sql);

  //die('stop');
  $sql = "SELECT SQL_CALC_FOUND_ROWS ".
           "t.id as topic_id, t.subject as t_subject, ".
           "u.name as t_author, count(p.id) as numreplies, ".
           "t.date_posted as t_posted, tmp.postdate as re_posted ".
         "FROM forum_users u ".
         "JOIN forum_posts t ".
         "ON t.author_id = u.id ".
         "LEFT JOIN tmp ".
         "ON t.id = tmp.topic_id ".
         "LEFT JOIN forum_posts p ".
         "ON p.topic_id = t.id ".
         "WHERE t.forum_id = $forumid ".
         "AND t.topic_id = 0 ".
         "GROUP BY t.id ".
         "ORDER BY re_posted DESC " .
         "LIMIT $start, $limit";
  $result = mysql_query($sql)
    or die(mysql_error()."<br>".$sql);
    $numrows = mysql_num_rows($result);
  if ($numrows == 0) {
    $msg = "There are currently no posts.  Would you " .
           "like to be the first person to create a thread?";
    $title = "Welcome to " . $forum['name'];
    $dest = "compose.php?forumid=" . $forumid;
    $sev = "Info";
    $message = msgBox($msg,$title,$dest,$sev);
    echo $message;
  } else {
    if (isset($_SESSION['user_id'])) {
      echo topicReplyBar(0, $_GET['f'], "right");
    }
    echo "<table class='forumtable' cellspacing='0' ";
    echo "cellpadding='2'><tr>";
    echo "<th class='thread'>Thread</th>";
    echo "<th class='author'>Author</th>";
    echo "<th class='replies'>Replies</th>";
    echo "<th class='lastpost'>Last Post</th>";
    echo "</tr>";
    while ($row = mysql_fetch_array($result)) {
      $rowclass = ($rowclass == "row1"?"row2":"row1");
      if ($row['re_posted']=="") {
        $lastpost = $row['t_posted'];
      } else {
        $lastpost = $row['re_posted'];
      }
      if ((isset($_SESSION['user_id'])) and
         ($_SESSION['last_login'] < $lastpost)) {
        $newpost = true;
      } else {
        $newpost = false;
      }
      echo "<tr class='$rowclass'>";
      echo "<td class='thread'>".($newpost?NEWPOST."&nbsp;":"");
      echo "<a href='viewtopic.php?t=";
      echo $row['topic_id'] . "'>" . $row['t_subject'] . "</a></td>";
      echo "<td class='author'>" . $row['t_author'] . "</td>";
      echo "<td class='replies'>" . $row['numreplies'] . "</td>";
      echo "<td class='lastpost'>" . $lastpost . "</td>";
      echo "</tr>\n";
    }
    echo "</table>";
    echo paginate($limit);
    echo "<p>".NEWPOST." = New Post(s)</p>";
  }
  $sql = "DROP TABLE tmp;";
  mysql_query($sql) or die(mysql_error()."<br>".$sql);

require_once 'footer.php';
?>

compose.php - Try It Out 1

<?php
require_once 'conn.php';
require_once 'functions.php';
require_once 'header.php';

$subject = '';
$topicid = $_GET['topicid'];
$forumid = $_GET['forumid'];
$reid = $_GET['reid'];
$body = '';
$post = '';
$authorid = $_SESSION['user_id'];
$edit_mode=FALSE;

if (isset($_GET['a'])
    and $_GET['a'] == 'edit'
    and isset($_GET['post'])
    and $_GET['post']){
  $edit_mode=TRUE;
}

require_once 'header.php';

if (!isset($_SESSION['user_id'])) {
  echo "<div class='notice'>" .
       "You must be logged in to post.  Please <a href='" .
       "login.php'>Log in</a> before posting a message." .
       "</div>";
} elseif ($edit_mode and $_SESSION['user_id'] != $authorid) {
  echo "<div class='noauth'>" .
       "You are not authorized to edit this post.  Please contact " .
       "your administrator.</div>";
} else {
  if ($edit_mode) {
    $sql = "SELECT * FROM forum_posts p, forum_forum f " .
           "WHERE p.id = " . $_GET['post'].
           " AND p.forum_id = f.id";
    $result = mysql_query($sql,$conn)
      or die('Could not retrieve post data; ' . mysql_error());

    $row = mysql_fetch_array($result);

    $subject = $row['subject'];
    $topicid = $row['topic_id'];
    $forumid = $row['forum_id'];
    $body = $row['body'];
    $post = $_GET['post'];
    $authorid = $row['author_id'];
  } else {

    if ($topicid == "") {
      $topicid = 0;
      $topicname = "New Topic";
    } else {
      if ($reid != "") {
        $sql = "SELECT subject FROM forum_posts WHERE id = " . $reid;
        $result = mysql_query($sql,$conn)
          or die('Could not retrieve topic; ' . mysql_error());
        if (mysql_num_rows($result) > 0) {
          $row = mysql_fetch_array($result);
          $re = preg_replace("/(re: )/i","",$row['subject']);
        }
      }
      $sql = "SELECT subject FROM forum_posts WHERE id = ";
      $sql .= $topicid . " AND topic_id = 0 AND forum_id = $forumid;";
      $result = mysql_query($sql,$conn)
        or die('Could not retrieve topic; ' . mysql_error());
      if (mysql_num_rows($result) > 0) {
        $row = mysql_fetch_array($result);
        $topicname = "Reply to <em>" . $row['subject'] . "</em>\n";
        $subject = ($re == ""?"":"Re: " . $re);
      } else {
        $topicname = "Reply";
        $topicid = 0;
      }
    }
  }
  if ($forumid == "" or $forumid == 0) $forumid=1;
  $sql = "SELECT forum_name FROM forum_forum WHERE id = '";
  $sql .= $forumid . "'";
  $result = mysql_query($sql,$conn)
    or die('Could not retrieve forum name; ' . mysql_error());
  $row = mysql_fetch_array($result);
  $forumname = $row['forum_name'];

?>

  <form id="forumpost" method="post" action="transact-post.php">

  <h3><?php echo $edit_mode
                 ?"Edit Post"
                 :"$forumname: $topicname";?>
  </h3>
  <p>
    Subject:<br />
    <input type="text" class="subject" name="subject" maxlength="255"
      value="<?php echo $subject; ?>" />
  </p>
  <p>
    Body:<br />
    <textarea class="body" name="body" rows="10" cols="60"><?php
      echo $body; ?></textarea>
  </p>
  <p>
  <?php

  if ($edit_mode) {
    echo '<input type="submit" class="submit" name="action" ' .
         "value=\"Save Changes\" />\n";
  } else {
    echo '<input type="submit" class="submit" name="action" ' .
         "value=\"Submit New Post\" />\n";
  }
  ?>
  </p>
  <?php
  echo "<input type='hidden' name='post' value='$post'>\n";
  echo "<input type='hidden' name='topic_id' value='$topicid'>\n";
  echo "<input type='hidden' name='forum_id' value='$forumid'>\n";
  echo "<input type='hidden' name='author_id' value='$authorid'>\n";
  echo "</form>\n";
}
require_once 'footer.php';
?>

search.php - Try It Out 1

<?php
require_once 'conn.php';
require_once 'functions.php';
require_once 'header.php';

$result = NULL;
if (isset($_GET['keywords'])) {
  $sql = "SELECT *, MATCH (subject,body) " .
         "AGAINST ('" . $_GET['keywords'] . "') AS score " .
         "FROM forum_posts " .
         "WHERE MATCH (subject,body) " .
         "AGAINST ('" . $_GET['keywords'] . "') " .
         "ORDER BY score DESC";

  $result = mysql_query($sql,$conn)
    or die('Could not perform search; ' . mysql_error());
}

echo "<table class='forumtable' width='100%' " .
     "cellspacing='0'>\n";
echo "<tr><th class='searchHeader'>Search Results</th></tr>\n";

if ($result and !mysql_num_rows($result)) {
  echo "<tr class='row1'><td>No articles found that match the ";
  echo "search term(s) '<strong>" . $_GET['keywords'] . "</strong>'";
  if ($access_lvl > 2) echo "<p>SQL: $sql</p>";
  echo "</td></tr>\n";
} else {
  while ($row = mysql_fetch_array($result)) {
    $rowclass = ($rowclass == "row1"?"row2":"row1");
    echo "<tr class='$rowclass'>\n<td>\n";
    $topicid=($row['topic_id']==0?$row['id']:$row['topic_id']);
    echo "<p class='searchSubject'>\n<a href='viewtopic.php?t=" .
         $topicid . "#post" . $row['id'] . "'>" .
         $row['subject'] . "</a>\n";
    echo "</p>\n";
    echo "<p class='searchBody'>\n";
    echo htmlspecialchars(trimBody($row['body']));
    if ($access_lvl > 2) {
      echo "<br /><br />relevance: " . $row['score'];
    }
    echo "\n</p>\n";
    echo "</td>\n</tr>\n\n";
  }
}
echo "</table>";

require_once 'footer.php';
?>

transact-admin.php - Try It Out 1

<?php
session_start();
require_once 'conn.php';
require_once 'http.php';

if (isset($_REQUEST['action'])) {
  switch ($_REQUEST['action']) {
    case 'Add Forum':
      if (isset($_POST['forumname'])
          and $_POST['forumname'] != ""
          and isset($_POST['forumdesc'])
          and $_POST['forumdesc'] != "")
      {
        $sql = "INSERT IGNORE INTO forum_forum " .
               "VALUES (NULL, '" .
               htmlspecialchars($_POST['forumname'], ENT_QUOTES) .
               "', '" .
               htmlspecialchars($_POST['forumdesc'], ENT_QUOTES) .
               "', " . $_POST['forummod'][0] . ")";
        mysql_query($sql) or die(mysql_error());
      }
      redirect('admin.php?option=forums');
      break;
    case 'Edit Forum':
      if (isset($_POST['forumname'])
          and $_POST['forumname'] != ""
          and isset($_POST['forumdesc'])
          and $_POST['forumdesc'] != "")
      {
        $sql = "UPDATE forum_forum " .
               "SET forum_name = '" . $_POST['forumname'] .
               "', forum_desc = '" . $_POST['forumdesc'] .
               "', forum_moderator = " . $_POST['forummod'][0] .
               " WHERE id = " . $_POST['forum_id'];
        mysql_query($sql) or die(mysql_error());
      }
      redirect('admin.php?option=forums');
      break;
    case 'Modify User':
      redirect("useraccount.php?user=" . $_POST['userlist'][0]);
      break;
    case 'Update':
      foreach($_POST as $key => $value) {
        if ($key != 'action') {
          $sql = "UPDATE forum_admin SET value='$value' ".
                 "WHERE constant = '$key'";
          mysql_query($sql) or die(mysql_error());
        }
      }
      redirect('admin.php');
      break;
    case "deleteForum":
      $sql = "DELETE FROM forum_forum WHERE id=" . $_GET['f'];
      mysql_query($sql) or die(mysql_error());
      $sql = "DELETE FROM forum_posts WHERE forum_id=" . $_GET['f'];
      mysql_query($sql) or die(mysql_error());
      redirect('admin.php?option=forums');
      break;
    case "Add New":
      $sql = "INSERT INTO forum_bbcode " .
             "VALUES (NULL,'".
             htmlentities($_POST['bbcode-tnew'],ENT_QUOTES)."','".
             htmlentities($_POST['bbcode-rnew'],ENT_QUOTES)."');";
      mysql_query($sql) or die(mysql_error()."<br>".$sql);
      redirect('admin.php?option=bbcode');
      break;
    case "deleteBBCode":
      if (isset($_GET['b'])) {
        $bbcodeid = $_GET['b'];
        $sql = "DELETE FROM forum_bbcode WHERE id=" . $bbcodeid;
        mysql_query($sql) or die(mysql_error());
      }
      redirect('admin.php?option=bbcode');
      break;
    case 'Update BBCodes':
      foreach($_POST as $key => $value) {
        if (substr($key,0,7) == 'bbcode_') {
          $bbid = str_replace("bbcode_", "", $key);
          if (substr($bbid,0,1) == 't') {
            $col = "template";
          } else {
            $col = "replacement";
          }
          $id = substr($bbid,1);
          $sql = "UPDATE forum_bbcode SET $col='$value' ".
                 "WHERE id=$id";
          mysql_query($sql) or die(mysql_error());
        }
      }
      redirect('admin.php?option=bbcode');
      break;
    default:
      redirect('index.php');
  }
} else {
  redirect('index.php');
}
?>

transact-post.php - Try It Out 1

<?php
session_start();
require_once 'conn.php';
require_once 'http.php';

if (isset($_REQUEST['action'])) {
  switch (strtoupper($_REQUEST['action'])) {
    case 'SUBMIT NEW POST':
      if (isset($_POST['subject'])
          and isset($_POST['body'])
          and isset($_SESSION['user_id']))
      {
        $sql = "INSERT INTO forum_posts VALUES (" .
               "NULL," . $_POST['topic_id'] .
               "," . $_POST['forum_id'] .
               "," . $_SESSION['user_id'] .
               ",0" .
               ",'" . date("Y-m-d H:i:s",time()) .
               "',0" .
               ",'" . $_POST['subject'] .
               "','" . $_POST['body'] . "')";

        mysql_query($sql,$conn)
          or die('Could not post: ' . mysql_error() . "<br>$sql");
        $postid = mysql_insert_id();

        $sql = "INSERT IGNORE INTO forum_postcount VALUES (" .
               $_SESSION['user_id'] . ",0);";
        mysql_query($sql,$conn)
          or die(mysql_error());

        $sql = "UPDATE forum_postcount SET count = count + 1 " .
               "WHERE user_id = " . $_SESSION['user_id'];
        mysql_query($sql,$conn)
          or die(mysql_error());

      }
      $topicid=($_POST['topic_id']==0?$postid:$_POST['topic_id']);
      redirect('viewtopic.php?t=' . $topicid . '#post' . $postid);
      break;

    case 'NEW TOPIC':
      redirect('compose.php?f=' . $_POST['forum_id']);

    case 'EDIT':
      redirect('compose.php?a=edit&post=' . $_POST['topic_id']);
      break;

    case 'SAVE CHANGES':
      if (isset($_POST['subject'])
          and isset($_POST['body']))
      {
        $sql = "UPDATE forum_posts " .
               "SET subject='" . $_POST['subject'] .
               "', update_id=" . $_SESSION['user_id'] .
               ", body='" . $_POST['body'] . "', date_updated='" .
               date("Y-m-d H:i:s",time()) . "' " .
               "WHERE id=" . $_POST['post'];
        if (isset($_POST['author_id'])) {
          $sql .= " AND author_id=" . $_POST['author_id'];
        }

        mysql_query($sql,$conn)
          or die('Could not update post; ' . mysql_error());
      }
        $redirID = ($_POST['topic_id'] == 0?$_POST['post']:
          $_POST['topic_id']);
          redirect('viewtopic.php?t=' . $redirID);
      break;

    case 'DELETE':
      if ($_REQUEST['post']) {
        $sql = "DELETE FROM forum_posts " .
               "WHERE " . "id=" . $_REQUEST['post'];
        mysql_query($sql,$conn)
          or die('Could not delete post; ' . mysql_error());
      }
      redirect($_REQUEST['r']);
      break;
   }
} else {
  redirect('index.php');
}
?>

transact-user.php - Try It Out 1

<?php
require_once 'conn.php';
require_once 'http.php';

if (isset($_REQUEST['action'])) {
  switch ($_REQUEST['action']) {
    case 'Login':
      if (isset($_POST['email'])
          and isset($_POST['passwd']))
      {
        $sql = "SELECT id,access_lvl,name,last_login " .
               "FROM forum_users " .
               "WHERE email='" . $_POST['email'] . "' " .
               "AND passwd='" . $_POST['passwd'] . "'";
        $result = mysql_query($sql,$conn)
          or die('Could not look up user information; ' . mysql_error());

        if ($row = mysql_fetch_array($result)) {
          session_start();
          $_SESSION['user_id'] = $row['id'];
          $_SESSION['access_lvl'] = $row['access_lvl'];
          $_SESSION['name'] = $row['name'];
          $_SESSION['last_login'] = $row['last_login'];
          $sql = "UPDATE forum_users SET last_login = '".
                 date("Y-m-d H:i:s",time()) . "' ".
                 "WHERE id = ". $row['id'];
          mysql_query($sql,$conn)
          or die(mysql_error()."<br>".$sql);
        }
      }
      redirect('index.php');
      break;

    case 'Logout':
      session_start();
      session_unset();
      session_destroy();

      redirect('index.php');
      break;

    case 'Create Account':
      if (isset($_POST['name'])
          and isset($_POST['email'])
          and isset($_POST['passwd'])
          and isset($_POST['passwd2'])
          and $_POST['passwd'] == $_POST['passwd2'])
      {
        $sql = "INSERT INTO forum_users ".
               "(email,name,passwd,date_joined,last_login) " .
               "VALUES ('" . $_POST['email'] . "','" .
               $_POST['name'] . "','" . $_POST['passwd'] . "','".
               date("Y-m-d H:i:s",time()). "','".
               date("Y-m-d H:i:s",time()). "')";

        mysql_query($sql,$conn)
          or die('Could not create user account; ' . mysql_error());

        session_start();
        $_SESSION['user_id'] = mysql_insert_id($conn);
        $_SESSION['access_lvl'] = 1;
        $_SESSION['name'] = $_POST['name'];
        $_SESSION['login_time'] = date("Y-m-d H:i:s",time());
      }
      redirect('index.php');
      break;

    case 'Modify Account':
      if (isset($_POST['name'])
          and isset($_POST['email'])
          and isset($_POST['accesslvl'])
          and isset($_POST['userid']))
      {
        $sql = "UPDATE forum_users " .
               "SET email='" . $_POST['email'] .
               "', name='" . $_POST['name'] .
               "', access_lvl=" . $_POST['accesslvl'] .
               ", signature='" . $_POST['signature'] . "' " .
               " WHERE id=" . $_POST['userid'];

        mysql_query($sql,$conn)
          or die('Could not update user account... ' . mysql_error() .
                 '<br>SQL: ' . $sql);
      }
      redirect('admin.php');
      break;

    case 'Edit Account':
      if (isset($_POST['name'])
          and isset($_POST['email'])
          and isset($_POST['accesslvl'])
          and isset($_POST['userid']))
      {
        $chg_pw=FALSE;
        if (isset($_POST['oldpasswd'])
            and $_POST['oldpasswd'] != '') {
          $sql = "SELECT passwd FROM forum_users " .
                    "WHERE id=" . $_POST['userid'];
          $result = mysql_query($sql) or die(mysql_error());
          if ($row = mysql_fetch_array($result)) {
            if (($row['passwd'] == $_POST['oldpasswd'])
                and (isset($_POST['passwd']))
                and (isset($_POST['passwd2']))
                and ($_POST['passwd'] == $_POST['passwd2']))
            {
              $chg_pw = TRUE;
            } else {
              redirect('useraccount.php?error=nopassedit');
              break;
            }
          }
        }
        $sql = "UPDATE forum_users " .
               "SET email='" . $_POST['email'] .
               "', name='" . $_POST['name'] .
               "', access_lvl=" . $_POST['accesslvl'] .
               ", signature='" . $_POST['signature'];
        if ($chg_pw) {
          $sql .= "', passwd='" . $_POST['passwd'];
        }
        $sql .= "' WHERE id=" . $_POST['userid'];
        mysql_query($sql,$conn)
          or die('Could not update user account... ' . mysql_error() .
                 '<br>SQL: ' . $sql);
      }
      redirect('useraccount.php?blah=' . $_POST['userid']);
      break;

    case 'Send my reminder!':
      if (isset($_POST['email'])) {
        $sql = "SELECT passwd FROM forum_users " .
               "WHERE email='" . $_POST['email'] . "'";

        $result = mysql_query($sql,$conn)
          or die('Could not look up password; ' . mysql_error());

        if (mysql_num_rows($result)) {
          $row = mysql_fetch_array($result);

          $subject = 'Comic site password reminder';
          $body = "Just a reminder, your password for the " .
                  "Comic Book Appreciation site is: " . $row['passwd'] .
                  "\n\nYou can use this to log in at http://" .
                  $_SERVER['HTTP_HOST'] .
                  dirname($_SERVER['PHP_SELF']) . '/login.php?e='.
                  $_POST['email'];
          $headers = "From: admin@yoursite.com\r\n";

          mail($_POST['email'],$subject,$body,$headers)
            or die('Could not send reminder email.');
        }
      }
      redirect('login.php');
      break;
  }
}
?>

transact-affirm.php - Try It Out 1

<?php
require_once 'conn.php';
require_once 'functions.php';
require_once 'http.php';
require_once 'header.php';
?>
<script type='text/javascript'>
<!--
function deletePost(id,redir) {
  if (id > 0) {
    window.location = "transact-post.php?action=delete&post=" +
      id + "&r=" + redir;
  } else {
    history.back();
  }
}
function deleteForum(id) {
  if (id > 0) {
    window.location = "transact-admin.php?action=deleteForum&f=" + id;
  } else {
    history.back();
  }
}
//-->
</script>
<?php
switch (strtoupper($_REQUEST['action'])) {
  case "DELETEPOST":
    $sql = "SELECT * FROM forum_posts WHERE id=" . $_REQUEST['id'];
    $result = mysql_query($sql);
    $row = mysql_fetch_array($result);
    if ($row['topic_id'] > 0) {
      $msg = "Are you sure you wish to delete the post<br>".
        "<em>".$row['subject']."</em>?";
      $redir = htmlspecialchars("viewtopic.php?t=" . $row['topic_id']);
    } else {
      $msg = "If you delete this post, all replies will be deleted ".
        "as well.  Are you sure you wish to delete the entire ".
        "thread<br><em>".$row['subject']."</em>?";
      $redir = htmlspecialchars("viewforum.php?f=" . $row['forum_id']);
    }
    echo "<div id='requestConfirmWarn'>";
    echo "<h2>DELETE POST?</h2>\n";
    echo "<p>" . $msg . "</p>";
    echo "<p><input class='confirm' type='button' value='Delete' ";
    echo "onclick='deletePost(" . $row['id'] .
         ",\"" . $redir . "\");'>";
    echo "<input class='confirm' type='button' value='Cancel' ";
    echo "onclick='history.back()'></p>";
    echo "</div>";
    break;
  case "DELETEFORUM":
    $sql = "SELECT * FROM forum_forum WHERE id=" . $_REQUEST['f'];
    $result = mysql_query($sql);
    $row = mysql_fetch_array($result);
    $msg = "If you delete this forum, all topics and replies will be".
      " deleted as well.  Are you sure you wish to delete the entire ".
      "forum<br><em>".$row['forum_name']."</em>?";
    echo "<div id='requestConfirmWarn'>";
    echo "<h2>DELETE FORUM?</h2>\n";
    echo "<p>" . $msg . "</p>";
    echo "<p><input class='confirm' type='button' value='Delete' ";
    echo "onclick='deleteForum(" . $_REQUEST['f'] . ");'>";
    echo "<input class='confirm' type='button' value='Cancel' ";
    echo "onclick='history.back()'></p>";
    echo "</div>";

  default:
}
require_once 'footer.php';
?>