<?php

/*

bbshowpost.php

This is the main page for the forum - in it you can:

* log on
* log off
* make a post (ie. create a subject)
* reply to a post (ie. add to a subject)
* list all sections (main menu)
* list all topics in a section (topic menu)
* list all subjects in a topic (subject menu)
* view all posts in a subject 
* delete a message
* amend a message
* view statistics (count of messages)
* jump to a topic (topics combo-box)
* users are notified of new posts to topics/subjecs they have subscribed to
* forum codes are interpreted (eg. [b] for bold)


I would have preferred to make these functions more modular, but in many
cases they had shared functionality. 

eg. 

Adding a message also lists existing messages
Amending a message is similar to adding a message

I have made a bit of a start by
moving the contents of some functions to different files. Experimentation
shows that these files are only loaded if needed, thus the file with the
contents of "AddMessage" is only read if someone adds a message. That is why
the function *header* is in this file, but the function body in another. I
am trying to defer the parsing (and the time it takes) until absolutely needed.


Stand-alone pages which *are* in different php files are:

List forum codes (help page) - bbforumcode.php
Change password/request password mail out - bbpassword.php
Search for a message - bbsearch.php
Show a user's biography (email address etc.) - bbshowbio.php
Add/amend a user's details - bbuseredit.php
List all users - bbuserlist.php

Shared routines - common.php


Structure
---------

The forum is organised into sections, topics, subjects and posts. 
These are represented by the SQL tables bbsection, bbtopic, 
  bbsubject and bbpost respectively.

This is intended for a layout like this:

Major section (eg. product A)
  |
  |
  -- Topic (eg. Sales, Support, FAQ)
     |
     |
     -- Subject (eg. How do I turn on the power?)
        |
        |
        -- Post (eg. one message about the subject)

Sections and topics are entered manually, using the table editor, 
as normally the rate of change there will be small.

Users can start their own subjects, or reply to existing ones.

------------------------------------------
Copyright © 2001 Nick Gammon.

  Author: Nick Gammon <nick@gammon.com.au>
  Web:    http://www.gammon.com.au/
  Date:   February 2001

  This program is free software; you can redistribute it and/or modify 
  it under the terms of the GNU General Public License as published by 
  the Free Software Foundation; either version 2 of the License, 
  or (at your option) any later version. 

  This program is distributed in the hope that it will be useful, 
  but WITHOUT ANY WARRANTY; without even the implied warranty of 
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
  See the GNU General Public License for more details. 

  You should have received a copy of the GNU General Public License 
  along with this program; if not, write to 

  The Free Software Foundation, Inc., 
  59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.


  The Free Software Foundation maintains a web page at: http://www.fsf.org

  See the file gpl.txt for the full GNU General Public License.

*/

require ("config.php");
require ($CONFIG_PATH . "general_config.php");
require ($INCLUDE_DIRECTORY . "common.php");

Init ("%FORUM_NAME%", "forum, topics, subjects"); 

$MAX_MESSAGE_SIZE = 6000;
$MAX_SUBJECT_SIZE = 80;

// I use THIS_PAGE instead of PHP_SELF, because I am calling this entire
// page from forum.php, and I don't want forum.php to be re-called (because
// it will be in the wrong directory).

$THIS_PAGE = $control ['forum_url'] . '/bbshowpost.php';
$FORUM_URL = $control ['forum_url'] . '/';

function ShowTopicsComboBox ()
  {
  global $THIS_PAGE, $FORUM_URL;
  
  
  echo "<form METHOD=\"post\" ACTION=\"$THIS_PAGE\"> \n";
  echo "<p>Go to topic: &nbsp; <select name=\"bbtopic_id\" size=1>\n";

                         
  $result = mysql_query ("SELECT bbtopic.bbtopic_id, "
                       . "  concat(section_name, ': ', topic_name) "
                       . "AS description "
                       . "FROM bbtopic, bbsection "
                       . "WHERE bbsection.bbsection_id = bbtopic.bbsection_id  "
                       . "  AND bbtopic.bbtopic_id > 0 "
                       . "ORDER BY section_name, topic_name") 
    or Problem ("Select of topics failed: " . mysql_error ());
    
  echo "<option value=0 selected>(Choose topic)\n";
    
  while ($row = mysql_fetch_array ($result))
    {
    $id = $row ['bbtopic_id'];
    $desc = $row ['description'];
    echo "<option value=\"$id\">$desc\n";
    } // end of doing each row
  
  mysql_free_result ($result);
  
  echo "</select>\n";
  
  FormSession ();
  echo "&nbsp; &nbsp; <input Type=submit Value=\"Go\">&nbsp; &nbsp;\n";
  hLink ("Search the forum", $FORUM_URL . "bbsearch.php"); 
  echo "</p>";
  echo "</form>\n";


  }   // end of ShowTopicsComboBox
  
function MailUsers ($link, $username, $subject, $bbtopic_id, $bbsubject_id, $bbuser_id, $new)
  {
  global $FORUM_INCLUDE_DIRECTORY;
  require ($FORUM_INCLUDE_DIRECTORY . "bb_fnc_mailusers.php");
  } // end of MailUsers

function TranslateForumCode (&$message)
  {
  global $FORUM_INCLUDE_DIRECTORY;
  require ($FORUM_INCLUDE_DIRECTORY . "bb_fnc_translateforumcode.php");
  } // end of TranslateForumCode
    
function LookupSubject ()
  {
  global $bbsubject_id, $subjectrow;
  
  //-------------
  // lookup subject
  //-------------
  
  $query = "SELECT * "
         . "FROM bbsubject, bbtopic, bbsection "
         . "WHERE bbsubject.bbsubject_id = $bbsubject_id "
         . "AND   bbtopic.bbtopic_id = bbsubject.bbtopic_id "
         . "AND   bbsection.bbsection_id = bbtopic.bbsection_id ";
                           
  $result = mysql_query ($query) 
      or Problem ("Select of subject failed: " . mysql_error ());
    
  if (!($subjectrow = mysql_fetch_array ($result)))
      Problem ("Subject $bbsubject_id is not on file.");
  
  mysql_free_result ($result);
  
  } // end of LookupSubject

function LookupTopic ()
  {
  global $bbtopic_id, $topicrow, $THIS_PAGE;
  
  //-------------
  // lookup topic
  //-------------
  
  $query = "SELECT * "
         . "FROM  bbtopic, bbsection "
         . "WHERE bbtopic.bbtopic_id = $bbtopic_id "
          . "AND  bbsection.bbsection_id = bbtopic.bbsection_id ";
                           
  $result = mysql_query ($query) 
      or Problem ("Select of topic failed: " . mysql_error ());
    
  if (!($topicrow = mysql_fetch_array ($result)))
      Problem ("topic $bbtopic_id is not on file.");
  
  mysql_free_result ($result);
  
  } // end of LookupTopic
    
function GenerateHeader (&$header)
  {
  global $FORUM_INCLUDE_DIRECTORY;
  require ($FORUM_INCLUDE_DIRECTORY . "bb_fnc_generateheader.php");
  } // end of GenerateHeader
  
// this lists all sections

function ShowSections ()
  {
  global $FORUM_INCLUDE_DIRECTORY;
  require ($FORUM_INCLUDE_DIRECTORY . "bb_fnc_showsections.php");
  } // end of ShowSections  

// list all topics in a section

function ShowTopics ()
  {
  global $FORUM_INCLUDE_DIRECTORY;
  require ($FORUM_INCLUDE_DIRECTORY . "bb_fnc_showtopics.php");
  } // end of ShowTopics  

// list all subjects in a topic

function ShowSubjects ()
  {
  global $FORUM_INCLUDE_DIRECTORY;
  require ($FORUM_INCLUDE_DIRECTORY . "bb_fnc_showsubjects.php");
  } // end of ShowSubjects  

// show links (reply, new subject) for a subject

function ShowLinks ($subjectrow)
  {
  global $FORUM_INCLUDE_DIRECTORY;
  require ($FORUM_INCLUDE_DIRECTORY . "bb_fnc_showlinks.php");
  } // end of ShowLinks

// called after updating a posting, so that the subject count is correct

function UpdateSubject ($bbsubject_id)
  {
  global $FORUM_INCLUDE_DIRECTORY;
  require ($FORUM_INCLUDE_DIRECTORY . "bb_fnc_updatesubject.php");
  } // end of UpdateSubject   

function LogonForm ()
  {
  global $FORUM_INCLUDE_DIRECTORY;
  require ($FORUM_INCLUDE_DIRECTORY . "bb_fnc_logonform.php");
  } // end of LogonForm
      
function LogoffForm ()
  {
  global $FORUM_INCLUDE_DIRECTORY;
  require ($FORUM_INCLUDE_DIRECTORY . "bb_fnc_logoffform.php");
  } // end of LogoffForm        

function MessageForm ()
  {
  global $FORUM_INCLUDE_DIRECTORY;
  require ($FORUM_INCLUDE_DIRECTORY . "bb_fnc_messageform.php");
  } // end of MessageForm  
  
function AddMessage ()
{
  global $FORUM_INCLUDE_DIRECTORY;
  require ($FORUM_INCLUDE_DIRECTORY . "bb_fnc_addmessage.php");
} // end of AddMessage

function ConfirmDelete ()
  {
  global $FORUM_INCLUDE_DIRECTORY;
  require ($FORUM_INCLUDE_DIRECTORY . "bb_fnc_confirmdelete.php");
  } // end of ConfirmDelete
    
function DeleteMessage ()
  {
  global $FORUM_INCLUDE_DIRECTORY;
  require ($FORUM_INCLUDE_DIRECTORY . "bb_fnc_deletemessage.php");
  } // end of DeleteMessage
      
// ---------------- start of main section -------------------

// DEBUG

// DebugVars ();

// logon in common because we want to send the cookie before we start doing HTTP headers

// echo "Action = $action<br>";

// anchor for top of page

echo "<a name=top></a>\n";

if ($action == "logon")
  {
  
  // *now* we can show the error message
  if (!$foruminfo)
    if ($blocked)
      ShowError ("That username is not permitted to log on"); 
    else    
      ShowError ("That username/password combination is not on file"); 
  }
else if ($action == "logoff" && $foruminfo)
  {
  $bbuser_id = $foruminfo ['bbuser_id'];
  if ($bbuser_id)
    {
    // generate another random token - they won't know that one!
    srand ((double) microtime () * 1000000);
    $token = md5 (uniqid (rand ()));
    
    $query = "UPDATE bbuser SET token = '$token' "
            . "WHERE bbuser_id = $bbuser_id";
    $result = mysql_query ($query)
      or Problem ("Update of bbuser failed: " . mysql_error ());
    }
   $foruminfo = "";
  } // end of logoff wanted    

// validate input so we don't get sneaky SQL problems

CheckField ("message", $bbpost_id);
CheckField ("subject", $bbsubject_id);
CheckField ("topic", $bbtopic_id);
CheckField ("section", $bbsection_id);
CheckField ("user", $bbuser_id);
CheckField ("page", $page);

if ($action == 'add' || $action == 'Save' || 
    $action == 'Save Changes' || $action == 'amend')
  AddMessage ();
else
if ($action == "Confirm Delete")
  DeleteMessage ();


// work out our headings

GenerateHeader ($header);
  
// display logon/logoff stuff, and names of sections/topics/subjects (in $header)
  
if (!$foruminfo)
  LogonForm ();   // no forum into? let them log in
else  
  LogoffForm ();  // otherwise let them log off

if ($action == 'subscribe' && $foruminfo)
  {
  $bbuser_id = $foruminfo ['bbuser_id'];
  
  if ($bbsubject_id)
    {
    mysql_query ( "INSERT INTO bbnotify_subject (bbuser_id, bbsubject_id) "
                . " VALUES ($bbuser_id, $bbsubject_id)");            
  
    echo "<p><b>You have now subscribed to this subject.</b>\n";
    echo "&nbsp;<font size=1>";
    hLink ("Unsubscribe", $THIS_PAGE, "action=unsubscribe&bbsubject_id=$bbsubject_id");
    echo "</font></p>";
    } // end of subscribing to a subject
  else if ($bbtopic_id)
    {
    mysql_query ( "INSERT INTO bbnotify_topic (bbuser_id, bbtopic_id) "
                . " VALUES ($bbuser_id, $bbtopic_id)");            
  
    echo "<p><b>You have now subscribed to this topic.</b>\n";
    echo "&nbsp;<font size=1>";
    hLink ("Unsubscribe", $THIS_PAGE, "action=unsubscribe&bbtopic_id=$bbtopic_id");
    echo "</font></p>";
    } // end of subscribing to a topic
  
  $action = ""; // forget we did it
  } // end of subscribing
else if ($action == 'unsubscribe' && $foruminfo)
  {
  $bbuser_id = $foruminfo ['bbuser_id'];
  
  if ($bbsubject_id)
    {
    mysql_query ( "DELETE FROM bbnotify_subject "
                . "WHERE bbuser_id = $bbuser_id AND bbsubject_id = $bbsubject_id ");
  
    echo "<p><b>You have now unsubscribed from this subject.</b>\n";
    echo "&nbsp;<font size=1>";
    hLink ("Subscribe", $THIS_PAGE, "action=subscribe&bbsubject_id=$bbsubject_id");
    echo "</font></p>";
    } // end of unsubscribing from a subject
  else if ($bbtopic_id)
    {
    mysql_query ( "DELETE FROM bbnotify_topic "
                . "WHERE bbuser_id = $bbuser_id AND bbtopic_id = $bbtopic_id ");
  
    echo "<p><b>You have now unsubscribed from this topic.</b>\n";
    echo "&nbsp;<font size=1>";
    hLink ("Subscribe", $THIS_PAGE, "action=subscribe&bbtopic_id=$bbtopic_id");
    echo "</font></p>";
    } // end of unsubscribing from a topic
    
  $action = ""; // forget we did it
  } // end of unsubscribing

if ($action == 'delete')
  ConfirmDelete ();
else if ($action == 'add' || $action == 'Save' || 
         $action == 'amend' || $action == 'Save Changes' ||
         $action == "Confirm Delete")
  {
  if ($have_error)
    {
  ?>
  <hr>
  <h2>Error in submission</h2>
  <p>There were some errors in processing your submission.</p>
  <p>Please correct them and re-submit the form (by clicking on &quot;Save&quot;). Thank you.</p> 
    
  <?php  
    } // end of error in fields

  if ($have_error || $action == 'add' || $action == 'amend')
    MessageForm ();   // show the form on add/amend/error on save
  else
    if ($action == "Confirm Delete")
      if ($bbsubject_id)
        echo "<h3>Message deleted</h4><hr>\n";
      else
        {
        echo "<h3>Subject deleted</h4><hr>\n";
        ShowSubjects ();    // show subjects in this topic
        }
      
  if ($bbsubject_id)
    if ($action == 'add' || $action == 'amend')
      {
      echo "<hr>\n";
      echo "<h3>Subject review</h3>\n";
      }
    else
      {
      echo "<table border=0 cellpadding=5 bgcolor=\"#CD5C5C\" width=\"100%\">";
      echo "<tr bgcolor=\"#CD5C5C\" align=center>\n";
      echo "<th><font color=\"#FFFFFF\">\n<b>";
      echo (htmlspecialchars ($headingrow ['subject_name']));
      echo "</b></font></th></tr>\n";        
      echo "</table><hr>\n";
      }
  }
else
  if (!$bbsubject_id)
    {
    if ($bbtopic_id)
      ShowSubjects ();    // show subjects in this topic
    else if ($bbsection_id)
      ShowTopics ();    // show topics in this section
    else ShowSections ();   // just show all sections
    } // end of no subject specified
    
//if (($action == 'Save' && !$have_error && $bbsubject_id) || !$action)
if ($bbsubject_id && $action != "delete")
  {  
          
  LookupSubject ();
 
//  if ($action != 'add' && $action != 'Save')
  if (!$action)
    {

    echo "<hr>\n";    
    echo "<table border=0 cellpadding=5 bgcolor=\"#CD5C5C\" width=\"100%\">\n";
    echo "<tr bgcolor=\"#CD5C5C\" align=center>\n";
    echo "<th><font color=\"#FFFFFF\">\n<b>";
    echo (htmlspecialchars ($subjectrow ['subject_name']));
    echo "</b>\n</font></th></tr>\n";
    echo "</table>\n";
    ShowLinks ($subjectrow);
    echo "<hr>\n";
  
    }  // end of just viewing

  if ($foruminfo ['bbuser_id'] == $subjectrow ['author'] || $foruminfo ['admin'] ||
      $foruminfo ['moderator_topic'] == $headingrow ['bbtopic_id'] ||
      $foruminfo ['moderator_section'] == $headingrow ['bbsection_id']) 
      {
      echo "<p align=right><font size=1>";
      hLink ("Amend subject description", 
             "bbupdatesubject.php", "bbsubject_id=$bbsubject_id", false);
      if ($foruminfo ['admin'])
        {
        echo "&nbsp;[&nbsp;";
        hLink ("subject id=$bbsubject_id",
                $ADMIN_DIRECTORY . "edittable.php", 
                sprintf ("table=bbsubject&bbsubject_id=%d", $bbsubject_id));
        echo "&nbsp;]";
                
        } // end of begin an admin
      echo "</font></p>\n";                
      }  // end of begin an admin or moderator
     
  $datetimeformat = $control ['datetimeformat'];
  $tz = $foruminfo ['time_zone'];
  if (!$tz)
    $tz = 0;		// ensure zero and not blank

	// set up label for date fields
  if ($foruminfo ['time_zone'] != "")
    $utclabel = "";
	else  
    $utclabel = " (UTC)";
  
  // OK - time for multiple page stuff. Work out the first and last post number
  
  $count_posts = $subjectrow ['count_posts'];
  $posts_per_page = $control ['posts_per_page'];
  
  // don't divide by zero, or have one post per page :)
  if ($posts_per_page < 5)
    $posts_per_page = 20;
    
  $pages = floor ((($count_posts - 1) / $posts_per_page) + 1);

  // make sure requested page is in range

  if ($page < 1)
    $page = 1;  // too small, make 1
    
  if ($page > $pages)
    $page = $pages;   // too large, make maximum
  
  $first_post = (($page - 1) * $posts_per_page) + 1;
  $last_post = $first_post + $posts_per_page - 1;
  
  // show them what pages there are
  
  if ($pages > 1)
    {
    echo "<p align=right><b>Pages: ";
    for ($i = 1; $i <= $pages; $i++)
      {
      if ($i == $page)
        echo "$i&nbsp;";
      else
        {
        hLink ("$i", $THIS_PAGE, "bbsubject_id=$bbsubject_id&page=$i", false);
        echo "&nbsp;";
        }       
      } // end of doing each page
      
    echo "</b></p>\n";                
    }
    
  $query = "SELECT bbpost.*, T1.show_email, T1.bounced, "
         . "  T1.email, T1.username AS author, T1.country, T1.count_posts, "
         . "  T2.username AS modifier, T1.signature, "
         . "  DATE_FORMAT(DATE_ADD(post_date, INTERVAL $tz HOUR), '$datetimeformat') AS formatted_date, "
         . "  DATE_FORMAT(DATE_ADD(amend_date, INTERVAL $tz HOUR), '$datetimeformat') AS formatted_amend_date "
         . "FROM bbpost, bbuser AS T1 LEFT JOIN bbuser AS T2 "
         . "   ON T2.bbuser_id = bbpost.amended_by "
         . "WHERE bbsubject_id = $bbsubject_id "
         . "  AND T1.bbuser_id = bbpost.bbuser_id  "
         . "ORDER BY post_date "
         . "LIMIT $last_post";
  
  $result = mysql_query ($query) 
      or Problem ("Select of posts failed: " . mysql_error ());
      
  $lastid = "";
  $item = 0;
  while ($row = mysql_fetch_array ($result))
    {
    if (++$item < $first_post)
      continue;   // skip ones from previous pages
    
    $html = $row ['html'];
    $bbpost_id = $row ['bbpost_id'];
    
    if ($html)
      $answerformat = array ('html' => true);
    else
      $answerformat = array ('breaks' => true);

    shLink ($postedby, "<b>" . htmlentities ($row ['author']) . "</b>",
            $FORUM_URL . "bbshowbio.php", 
            sprintf ("bbuser_id=%d", $row ['bbuser_id']),
            true);  // new window
           
    $country = htmlentities ($row ['country']);
    
    if ($country && $country <> "(undisclosed)")
      $postedby .= "<font size=1>&nbsp;&nbsp;$country</font>";
      
    $count_posts = $row ['count_posts'];
    
    if ($count_posts)
      {
      $postedby .= "&nbsp;&nbsp;<font size=1>($count_posts post";
      if ($count_posts > 1)
        $postedby .= "s";   // plural!
      $postedby .= ")</font>";
      } // end of having done some posts
    
    if (!$row ['blocked'])
      {
      shLink ($biolink, "<img src=\"/images/bio.gif\" border=0 width=15 height=15 alt=\"[Biography]\">"
              . "&nbsp;bio", 
              $FORUM_URL . "bbshowbio.php", 
              sprintf ("bbuser_id=%d", $row ['bbuser_id']),
              true);  // new window

      $postedby .= "&nbsp;&nbsp;<font size=1>$biolink</font>";
      }       // end of user not blocked
    
    $message = $row ['post_text'];
      
    // now convert to html    
    if (!$html)
      {
      
      // now do "forum code"     
      if ($row ['forum_code'])
        {
        // if they used [code] we can't do a nl2br inside the code segment
        $origmessage = htmlentities ($message);
        $message = "";
        
        while (!(($i = strpos ($origmessage, "[code]")) === false))
          {
            // copy portion before [code]
          if ($i > 0)
            {
            $message .= nl2br (substr ($origmessage, 0, $i));  
            $origmessage = substr ($origmessage, $i); // rest of it
          }
          
          // find where code ends
          $i =  strpos ($origmessage, "[/code]"); 
          
          // not [/code] - assume goes to end of message
          if ($i === false)
            $i = strlen ($origmessage);
           
          // copy code portion without translating newlines
          $message .= substr ($origmessage, 0, $i);
          $origmessage = substr ($origmessage, $i); // rest of it          
        } // end of looking for code segments
        $message .= nl2br ($origmessage);  // take rest of message after final code segment
        TranslateForumCode ($message);
        }
      else
        $message =  nl2br (htmlentities ($message));
         
      }
            
    // add signature
    $signature = $row ['signature'];
    
    $fullmessage = "<table width=\"100%\"><tr><td><font size=2>$message</font></td></tr>";

    // signature
          
    if ($signature)
        $fullmessage .= "<tr><td><hr color=\"#C0C0C0\">\n<font size=1 color=\"#808080\">" 
                      . nl2br (htmlentities ($signature)) 
                      . "</font></td></tr>";
    
    // add "go to top" icon
    
    $fullmessage .= "<tr align=right><td><font size=1>"
                  . "<a href=\"#top\">"
                  . "<img src=\"/images/gototop.gif\" alt=\"[Go to top]\" width=15 height=15 border=0>"
                  . "&nbsp;top</a>"
                  . "</font></td></tr>";
    
    $fullmessage .= "</table>\n";
  
    $formatted_date = $row ['formatted_date'];
    
    // get rid of postings at exactly midnight
    if (substr ($formatted_date, -8) == "12:00 AM")
      $formatted_date = substr ($formatted_date, 0,
                                strlen ($formatted_date) - 8);
      
    $post_date = htmlentities ($formatted_date) . $utclabel;

    // the poster, or an admin can modify the message
    if ($row ['bbuser_id'] == $foruminfo ['bbuser_id'] || $foruminfo ['admin'] ||
        $foruminfo ['moderator_topic'] == $headingrow ['bbtopic_id'] ||
        $foruminfo ['moderator_section'] == $headingrow ['bbsection_id']) 
      {
      
     if ($control ['allow_edits'])
        {
        shLink ($amendlink, "<img src=\"/images/post_edit.gif\" border=0 width=15 height=15 alt=\"[Edit message]\">\n"
         . "&nbsp;edit", $THIS_PAGE, "action=amend&bbpost_id=$bbpost_id&page=$page");
  
        $post_date .= "&nbsp;&nbsp;<font size=1>$amendlink</font>";
        } // end of edits allowed
        
     if ($control ['allow_deletes'])
        {
        shLink ($deletelink, "<img src=\"/images/post_delete.gif\" border=0 width=15 height=15 alt=\"[Delete message]\">\n"
         . "&nbsp;delete", $THIS_PAGE, "action=delete&bbpost_id=$bbpost_id&page=$page"); 
  
        $post_date .= "&nbsp;&nbsp;<font size=1>$deletelink</font>";
        } // end of deletes allowed      
      }      

    // let's record the message id for admins
    
    if ($foruminfo ['admin'])
      {
      shLink ($adminlink, "bbpost_id=$bbpost_id",
              $ADMIN_DIRECTORY . "edittable.php", 
              sprintf ("table=bbpost&bbpost_id=%d", $bbpost_id));
      $post_date .= "&nbsp;&nbsp;<font size=1>[&nbsp;$adminlink&nbsp;]</font>";
      } // end of showing the link to edit the message
              
    if ($row ["formatted_amend_date"] != $row ["formatted_date"])
      {
      shLink ($biolink, htmlentities ($row ['modifier']),
              $FORUM_URL . "bbshowbio.php", 
              sprintf ("bbuser_id=%d", $row ['amended_by']),
              true);  // new window

      $formatted_amend_date = $row ['formatted_amend_date'];
      
      // get rid of postings at exactly midnight
      if (substr ($formatted_amend_date, -11) == "12:00:00 AM")
        $formatted_amend_date = substr ($formatted_amend_date, 0,
                                  strlen ($formatted_amend_date) - 11);
      
      $post_date .= "<p><font size=1>Amended on " . htmlentities ($formatted_amend_date) 
       					 . $utclabel
                 . " by " . $biolink . "</font></p>";
      }
    $table = array 
      (
      'Posted by' => $postedby,  
      'Date' => $post_date,   
      'Message' => $fullmessage,
      );  // end of array
  
    echo "<a name=\"$bbpost_id\"></a>\n";
        
    ShowTable ($table,  // the data
              array (     // table parameters
                    'table' => 'border=0 cellpadding=5 width="100%"',
                    'LH' => 'valign=top bgcolor="#ADD8E6" align=right width="10%"',
                    'RH' => 'bgcolor="#FAF0E6" align=left'
                    ),
              array (     // specials
                    'Posted by'   => array ('html' => true),    // it might be a hyperlink
                    'Date'     => array ('html' => true),  
                    'Message'     => array ('html' => true),  
                    )
              );
          
    echo "<hr>\n";
    } // end of doing each post

	// warn them if times are in UTC time
	
  if (mysql_num_rows ($result) > 0)
    {
    if ($foruminfo ['time_zone'] == "")
      {
	    echo "<font size=1>\n";
	    echo "<p>The dates and times for posts above are shown in Universal Co-ordinated Time (UTC).</p>\n";     	
      
	  	if ($foruminfo)
		    echo "<p>To show them in your local time you can set the ";
			else
		    echo "<p>To show them in your local time you can join the forum, and then set the ";
		    	
	    echo "'time correction' field in your profile to the number of hours difference between ";
	    echo "your location and UTC time.</p>\n";
      echo "</font><hr>\n";
      }	// end of time zone 0
  }	// end of having any posts
  
  mysql_free_result ($result);


  // show all pages again
  
  if ($pages > 1)
    {
    echo "<p><b>This is page $page, subject is $pages pages long: ";
    if ($page > 1)
      {
      echo "&nbsp;";
      hLink ("<img src=\"/images/thin_prev.gif\" alt=\"[Previous page]\" "
           . "align=bottom border=0 width=73 height=18>", 
             $THIS_PAGE, "bbsubject_id=$bbsubject_id&page=" . ($page - 1), false);
      echo "&nbsp;";
      }
    
    for ($i = 1; $i <= $pages; $i++)
      {
      if ($i == $page)
        echo "$i&nbsp;";
      else
        {
        hLink ("$i", $THIS_PAGE, "bbsubject_id=$bbsubject_id&page=$i", false);
        echo "&nbsp;";
        }       
      } // end of doing each page
      
    if ($page < $pages)
      hLink ("<img src=\"/images/thin_next.gif\" alt=\"[Next page]\" "
           . "align=bottom border=0 width=73 height=18>", 
             $THIS_PAGE, "bbsubject_id=$bbsubject_id&page=" . ($page + 1), false);
    echo "</b></p>\n";                
    }

  if ($foruminfo ['admin'])
    {
      
    $bbuser_id = $foruminfo ['bbuser_id'];
    
    $query = "SELECT username, bbuser.bbuser_id "
           . "FROM bbuser, bbnotify_subject "
           . "WHERE bbsubject_id = $bbsubject_id "
           . "  AND   bbuser.bbuser_id = bbnotify_subject.bbuser_id "
 //          . "  AND   bbuser.bbuser_id <> $bbuser_id "                         
           . "  AND  (bbuser.bounced IS NULL OR bbuser.bounced = 0) "
           . "ORDER BY username";
    
              
    $result = mysql_query ($query) 
      or Problem ("Select of notification failed: " . mysql_error ());
  
    if (mysql_num_rows ($result) > 0)
      {
      echo "<p><b>Subscribed to by ...</b></p>\n";
      bList ();
      while ($row = mysql_fetch_array ($result))
        {
        $notifyname = $row ['username'];
        LI ();
        hLink (htmlspecialchars ($row ['username']),
               "bbshowbio.php",
               "bbuser_id=" . $row ['bbuser_id']
               );
    
        } // end of subscription loop
         
       eList ();
      } 
    mysql_free_result ($result);

  
  } // end of admin
   
  ShowLinks ($subjectrow);
  
  // count number of times viewed
  mysql_query ("UPDATE bbsubject SET count_views = count_views + 1 "
             . "WHERE bbsubject_id = $bbsubject_id")
    or Problem ("Update of bbsubject failed: " . mysql_error ());
  
  if ($foruminfo)   // only if logged in
    {
    // have they subscribed to this subject?
    
    $bbuser_id = $foruminfo ['bbuser_id'];
    
    $query = "SELECT * "
           . "FROM bbnotify_subject "
           . "WHERE bbsubject_id = $bbsubject_id "
           . "AND   bbuser_id = $bbuser_id ";
                                 
    $result = mysql_query ($query) 
        or Problem ("Select of subscription failed: " . mysql_error ());
      
    $subscribed = mysql_fetch_array ($result);
      
    mysql_free_result ($result);
  
    echo "<p>";
    
    if ($subscribed)
      {
      hLink ("Unsubscribe", $THIS_PAGE, "action=unsubscribe&bbsubject_id=$bbsubject_id");
      echo "&nbsp;Click to stop receiving email notification of replies.</p>\n";    
      $subscribed = true;	// otherwise it is an array
      }
    else
      {
      hLink ("Subscribe", $THIS_PAGE, "action=subscribe&bbsubject_id=$bbsubject_id");
      echo "&nbsp;Click to receive email notification of replies.</p>\n";
      $subscribed = false;	// otherwise it is an array
      } // end of not subscribed yet  
    }   // end of logged in

  ShowTopicsComboBox ();
    
  echo "<hr>\n";
  
  } // end of need to show this subject
else
  {
  ShowTopicsComboBox ();
  echo "<hr>";
  }
  
  
echo "<p align=right><font size=1><a href=\"#top\">"
   . "<img src=\"/images/gototop.gif\" alt=\"[Go to top]\" width=15 height=15 border=0>"
   . "&nbsp;top</a>"
   . "</font></p>\n";
 
MessageTail ();
?>
