<?php


// contents of function AddMessage

/*

Copyright © 2001 Nick Gammon.

  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. 

*/

global $bbtopic_id, $bbsubject_id, $subject, $bbpost_id, $have_error,
       $subject, $username, $password, $contents, $forum_code, 
       $html, $post_date, $subscribe,
       $action, $MAX_MESSAGE_SIZE, $THIS_PAGE, $FORUM_URL,
       $MAX_SUBJECT_SIZE, $foruminfo, $headingrow, $specials,
       $control, $subjectrow, $topicrow, $page;

// check they can do it

if (($action == 'amend' || $action == 'Save Changes') && !$control ['allow_edits'])
  Problem ("Messages cannot be edited at present");
if (($action == 'add' || $action == 'Save') && !$control ['allow_edits'])
  Problem ("Messages cannot be posted at present");
  
if ($bbpost_id)
  {
  $query = "SELECT * FROM bbpost, bbsubject, bbtopic "
         . "WHERE bbpost_id = $bbpost_id "
         . "  AND   bbsubject.bbsubject_id = bbpost.bbsubject_id "
         . "  AND   bbtopic.bbtopic_id = bbsubject.bbtopic_id ";
    
//  echo $query;
                        
  $result = mysql_query ($query) 
      or Problem ("Select of message failed: " . mysql_error ());
    
  if (($row = mysql_fetch_array ($result)))
    {
    $bbsubject_id = $row ['bbsubject_id'];
    $headingrow ['subject_name'] = $row ['subject_name'];
    $headingrow ['author'] = $row ['author'];
    if ($row ['bbuser_id'] != $foruminfo ['bbuser_id'] && 
                    !($foruminfo ['admin'] ||
                     $foruminfo ['moderator_topic'] == $row ['bbtopic_id'] ||
                     $foruminfo ['moderator_section'] == $row ['bbsection_id']))
      Problem ("You did not post this message");
    }
  else
    Problem ("Message $bbpost_id is not on file");

  mysql_free_result ($result);
  
  } // getting the message details and subject ID
    
if (!$foruminfo)
  {
  shLink ($registerlink, "Register forum user name", 
          $FORUM_URL . "bbuseredit.php", 
          "", true);
  shLink ($passwordlink, "Forgotten password?", 
          $FORUM_URL . "bbpassword.php", 
          "action=forgot", true);    
  } // end of not being logged in  
         
shLink ($forumcodelink, "What are forum codes?", 
        $FORUM_URL . "bbforumcode.php", 
        "", true);    

$specials = array
  (
  'subject'     => array (
                'description' => 'Subject:',
                'size' => 60,
                'maxlength' => $MAX_SUBJECT_SIZE
                ),    // subject
  'username'     => array (
                'input' => 'username',
                'description' => 'Name:',
                'comment' => 'Your forum user name.',
                'htmlcomment' => $registerlink,
                'size' => 30,
                'maxlength' => 30
                ),    // name
  'password'     => array (
                'input' => 'password',
                'type' => 'password',
                'description' => 'Password:',
                'comment' => 'Your forum password.',
                'htmlcomment' => $passwordlink,
                'size' => 20,
                'maxlength' => 20
                ),    // password
  'contents' => array (
                'input' => 'contents',
                'type' => 'multiline',
                'description' => 'Message:',
                'comment' => "Message to be posted \n"
                           . "Maximum of $MAX_MESSAGE_SIZE characters. Text only please, no HTML.",
                'rows' => 20,
                'cols' => 60
                ),    // contents
  'forum_code' => array (
                'input' => 'forum_code',
                'type' => 'bool',
                'description' => 'Forum codes:',
                'comment' => "Check this if you want to use 'forum codes'",
                'htmlcomment' => $forumcodelink,
                ),    // forum_code
  'html' => array (
                'input' => 'html',
                'type' => 'bool',
                'description' => 'Use HTML:',
                'comment' => "Check this if the post is in HTML",
                ),    // html
  'subscribe' => array (
                'input' => 'subscribe',
                'type' => 'bool',
                'description' => 'Subscribe:',
                'comment' => "Check to receive replies to this post",
                ),    // subscribe
  'post_date' => array (
                'input' => 'post_date',
                'size' => 25,
                'description' => 'Post date:',
                'comment' => "Date message was posted",
                ),    // post_date
  );  // end of specials

// amend description for contents if they are allowed unlimited length posts.
if ($foruminfo ['admin'] || 
    $foruminfo ['moderator_topic'] == $subjectrow ['bbtopic_id'] ||
    $foruminfo ['moderator_section'] == $subjectrow ['bbsection_id'] ||
    $foruminfo ['unlimited_post_length']
		)
   $specials ['contents'] ['comment'] = "Message to be posted.";
   
// They can add a subject if a new topic
if (!$bbsubject_id)
 {
 $specials ['subject'] ['input'] = 'subject';
 $specials ['subject'] ['comment'] = "Please provide a helpful subject description, "
                                  .  "not just 'a question', or similar.\n"
                                  .  "Maximum of $MAX_SUBJECT_SIZE characters.";
 LookupTopic ();
 $subjectrow = $topicrow; // for test below
 }
else
  {
  $specials ['subject'] ['heading'] = true;
  
  LookupSubject ();
  if ($subjectrow ['closed'] && !($foruminfo ['admin'] ||
      $foruminfo ['moderator_topic'] == $subjectrow ['bbtopic_id'] ||
      $foruminfo ['moderator_section'] == $subjectrow ['bbsection_id'])) 
    Problem ("This subject is now closed");
  }   // end of having a subject

if ($subjectrow ['admin_only'] && !($foruminfo ['admin'] ||
    $foruminfo ['moderator_topic'] == $subjectrow ['bbtopic_id'] ||
    $foruminfo ['moderator_section'] == $subjectrow ['bbsection_id'])) 
 Problem ("This topic can only be posted to by administrators or moderators");

if ($action == 'Save' || $action == 'Save Changes')
  {
  
  // must have a subject if no subject id
  if (!$bbsubject_id)
    ValidateOneField ('subject', 'text', true, $MAX_SUBJECT_SIZE, $specials);
    
  if (!$foruminfo)
    {   // only validate if not logged on
    ValidateOneField ('username', 'text', true, 30, $specials);
    ValidateOneField ('password', 'text', true, 20, $specials);
    } // end of not having a login
  else
    if ($username && $foruminfo ['admin'])  // for admins, validate they gave a good name
      ValidateOneField ('username', 'text', true, 30, $specials);
        
  // admins can post any length contents, as can moderators or others with permission
  ValidateOneField ('contents', 'text', true, 
                    $foruminfo ['admin'] || 
                    $foruminfo ['moderator_topic'] == $subjectrow ['bbtopic_id'] ||
                    $foruminfo ['moderator_section'] == $subjectrow ['bbsection_id'] ||
                    $foruminfo ['unlimited_post_length']
                     ? 0 : $MAX_MESSAGE_SIZE, $specials);

  ValidateOneField ('forum_code', 'bool', false, 1, $specials);
  ValidateOneField ('subscribe', 'bool', false, 1, $specials);

  if ($foruminfo ['htmlpost'])
    ValidateOneField ('html', 'bool', false, 1, $specials);

  if ($foruminfo ['admin'])
    {
          
    if ($control ['amend_post_date'])
       ValidateOneField ('post_date', 'datetime', false, 25, $specials);
    
    } // end of being an administrator
    
  // check user on file

/*
 --------- User not logged on ---------
*/
  if (!$foruminfo)
    {   
    if (!$specials ['username'] ['error'] &&
        !$specials ['password'] ['error']) 
      {
      $query = "SELECT * "
             . "FROM bbuser "
             . "WHERE username = '$username' "
             . "AND   password = '$password' ";
       
      // echo $query;
                            
      $result = mysql_query ($query) 
          or Problem ("Select of user failed: " . mysql_error ());
        
      if (!($userrow = mysql_fetch_array ($result)))
        {
        $specials ['username'] ['error'] =
          "Either this user is not on file, or has a different password";
        $specials ['password'] ['error'] =
          "Wrong password for this user";
        $have_error = true;
        }
      else
        {
        if ($userrow ['blocked'])
          {
          $specials ['username'] ['error'] =
            "This user is not permitted to make posts";
          $have_error = true;          
          }
        else
          {
          $bbuser_id = $userrow ['bbuser_id'];
          $last_post_hash = $userrow ['last_post_hash'];
          $last_post_subject = $userrow ['last_post_subject'];
          }
        }
      
      mysql_free_result ($result);
      }   // end of no error in user name or password
    }   // end of not logged on
  else
/*
 --------- Admin posting under a different name ---------
*/
    if ($action == 'Save' && 
        $foruminfo ['admin'] && 
        $control ['post_under_different_name'] &&
        $username
        )
    {
    if (!$specials ['username'] ['error']) 
      {
      $query = "SELECT * "
             . "FROM bbuser "
             . "WHERE username = '$username' ";
       
      // echo $query;
                            
      $result = mysql_query ($query) 
          or Problem ("Select of user failed: " . mysql_error ());
      if (!($userrow = mysql_fetch_array ($result)))
        {
        $specials ['username'] ['error'] =
          "This user is not on file";
        $have_error = true;
        }
      else
        {
        $bbuser_id = $userrow ['bbuser_id'];
        $last_post_hash = $userrow ['last_post_hash'];
        $last_post_subject = $userrow ['last_post_subject'];
        }
      mysql_free_result ($result);
      }   // end of no error in user name     
    } // end of posting under another name
  else
/*
 --------- User logged on ---------
*/
    { // logged on
    $bbuser_id = $foruminfo ['bbuser_id'];
    $username = $foruminfo ['username'];
    $last_post_hash = $foruminfo ['last_post_hash'];
    $last_post_subject = $foruminfo ['last_post_subject'];
    } // end of logged on

  // calculate hash of post contents
  
  $post_hash = md5 ($contents);
    
  // add subject if necessary
  
  if (!$have_error &&       // don't bother if errors
      !$bbsubject_id &&     // nor if they already have a subject
      $last_post_hash != $post_hash) // nor for a duplicate post
    {
    $query = "INSERT INTO bbsubject ("
           . "bbtopic_id, subject_name, author "
           . ") VALUES ("
           . "'$bbtopic_id', "
           . "'$subject', "
           . "'$bbuser_id' "
           . ")";
           
//    echo $query . "<br>";         
    
    $result = mysql_query ($query) 
      or Problem ("Insert failed: " . mysql_error ());
    if (mysql_affected_rows () == 0)
      Problem ("Could not insert record");
    $bbsubject_id = mysql_insert_id ();
    $newsubject = true;
    } // end of no error yet
  else
    $newsubject = false;
  

  } // end of save requested

if (!$have_error && ($action == 'Save' || $action == 'Save Changes'))
  {
  if ($bbpost_id)  // amending post
    {

    $extra_stuff = "";

    if ($foruminfo ['htmlpost'])
      $extra_stuff = "html = '$html', ";

    if ($foruminfo ['admin'])
      {
      
      if ($control ['amend_post_date'])
        $extra_stuff .= "post_date = '$post_date', ";
      
      } // end of being an administrator
    
    $query = "UPDATE bbpost SET "
           . "post_text = '$contents', amend_date = "
           . "'" . strftime ("%Y-%m-%d %H:%M:%S", utctime()) . "', "
           . "forum_code = '$forum_code', "
           . $extra_stuff
           . "amended_by = $bbuser_id "
           . "WHERE bbpost_id = $bbpost_id";
           
 //   echo $query . "<br>";         
    
    $result = mysql_query ($query) 
      or Problem ("Update failed: " . mysql_error ());
    
    // get subject name and topicid for mail message
    LookupSubject ();
    $subject = $subjectrow ['subject_name'];

  // update record for that subject, to make sorting easier
      
    UpdateSubject ($bbsubject_id);

    MailAdmins ("Updated: $subject", "updated a message about: $subject", 
                "/?bbsubject_id=$bbsubject_id#$bbpost_id",
                "notify_amend");
    
    } // end of amending post

  else 
    {   // adding post
    if ($last_post_hash != $post_hash) //  silently discard duplicate posts  
      {     
      
      $postdate = strftime ("%Y-%m-%d %H:%M:%S", utctime());

      if ($foruminfo ['admin'])
        {
        if ($control ['amend_post_date'] && $post_date)
          $postdate = "$post_date";
        } // end of being an administrator

      if (!$foruminfo ['htmlpost'])
        $html = "0";
      
      $query = "INSERT INTO bbpost ("
             . "bbsubject_id, bbuser_id, post_text, post_date, amend_date, forum_code, html "
             . ") VALUES ("
             . "'$bbsubject_id', "
             . "'$bbuser_id', "
             . "'$contents', "
             . "'$postdate', "
             . "'$postdate', "
             . "'$forum_code', "
             . "'$html' "
             . ")";
             
  //    echo $query . "<br>";         
            
      $result = mysql_query ($query) 
        or Problem ("Insert failed: " . mysql_error ());
      if (mysql_affected_rows () == 0)
        Problem ("Could not insert record");
      $bbpost_id = mysql_insert_id ();
        
  // update record for that user (count of posts, date of last post)
  
      $date_posted = strftime ("%Y-%m-%d %H:%M:%S", utctime());
      
      $query = "UPDATE bbuser SET count_posts = count_posts + 1, "
             . "last_post_date = '$date_posted', "
             . "last_post_subject = '$bbsubject_id', "
             . "last_post_hash = '$post_hash' "
             . "WHERE bbuser_id = $bbuser_id";
      $result = mysql_query ($query)
        or Problem ("Update of bbuser failed: " . mysql_error ());
    
  // update record for that subject, to make sorting easier
      
    UpdateSubject ($bbsubject_id);
     
    // get subject name and topicid for mail message
    LookupSubject ();
    $subject = $subjectrow ['subject_name'];
    $bbtopic_id = $subjectrow ['bbtopic_id'];

    // work out what page it is on
        
    $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;
      
    // this will be the page this post is on - useful for the email message
    $page = floor ((($count_posts - 1) / $posts_per_page) + 1);
    
    $link = "/?bbsubject_id=$bbsubject_id&page=$page#$bbpost_id";
       
    MailAdmins ("Post: $subject", "posted a new message about: $subject", 
                $link, "notify_add", $bbuser_id);
            
    // notify all users that want to be notified, about this posting
    
    MailUsers ($link, $username, $subject, $bbtopic_id, $bbsubject_id, $bbuser_id, $newsubject);
    } // end of not a duplicate
  else
    { // duplicate message - no write to database
    $bbsubject_id = $last_post_subject;   // so we re-display that subject correctly
    $page = 999999;     // force display of latest page - which should have this message on it
    } // end of duplicate message
      
  } // end of add new post

// subscribe/unsubscribe them

  if ($subscribe)
     mysql_query ( "INSERT INTO bbnotify_subject (bbuser_id, bbsubject_id) "
                  . " VALUES ($bbuser_id, $bbsubject_id)");            
  else
     mysql_query ( "DELETE FROM bbnotify_subject "
                 . "WHERE bbuser_id = $bbuser_id AND bbsubject_id = $bbsubject_id ");
            
  } // end of save or amend
  
?>
