<?PHP
#
#   FILE:  SPT--Forum.php
#
#   FUNCTIONS PROVIDED:
#       Forum->Forum($ForumId)
#           - constructor
#       Forum->ForumId()
#       Forum->ForumName()
#       Forum->ForumDescription()
#       Forum->TopicCount()
#       Forum->MessageCount()
#       Forum->ModeratorId()
#           - methods to retrieve resource attributes
#
#   Part of the Scout Portal Toolkit
#   Copyright 2002 Internet Scout Project
#   http://scout.cs.wisc.edu
#

/**
 * A converastion forum which includes topics and messages.
 * \nosubgrouping
 */

class Forum {

    # ---- PUBLIC INTERFACE --------------------------------------------------

    # Error codes for the forum object
    const OK = 0;
    const NONEXISTENT = 1;

    /** @name Setup/Initialization/Destruction */
    /*@{*/

    /** Object Constructor.
     * After constructing the object, be sure to call GetErrorStatus() and verify
     * that it returns Forum::OK.
     * @param ForumId The Id number of the forum to retrieve from the database,
     *   or -1 to create a new forum
     */
    function Forum($ForumId = NULL)
    {
        $this->ErrorStatus = Forum::OK;
        # locate class in database
        $this->DB = new SPTDatabase();
        $DB = $this->DB;
        # if ID supplied
        if ($ForumId !== NULL)
        {
            $this->ForumId = intval($ForumId);
            $DB->Query("SELECT * FROM Forums WHERE ForumId = "
                    .$this->ForumId);

            # if row was loaded
            if ($DB->NumRowsSelected() > 0)
            {
                # set attributes to values returned by database
                $this->DBFields = $DB->FetchRow();
            }
            else
            {
                $this->ErrorStatus = Forum::NONEXISTENT;
            }
        }
        elseif (func_num_args()==0)
        {
            # add record to database with that ID
            $DB->Query("INSERT INTO Forums (ForumId) VALUES (NULL)");
            $this->ForumId = $DB->Query("SELECT LAST_INSERT_ID() AS ForumId"
                    ." FROM Forums", "ForumId");
        }
        else
        {
            $this->ErrorStatus = Forum::NONEXISTENT;
        }

    }

    /**
     * Remove this forum, deleting all assocated topics and messages
     */
    function Delete()
    {
        if ($this->ErrorStatus == Forum::OK)
        {
            $this->DB->Query("Select * from Topics where ForumId = ".
                             $this->ForumId." ORDER BY DateCreated Desc");

            # get list of topics for this forum
            while ($Entry = $this->DB->FetchRow())
            {
                $Topic = new Topic($Entry["TopicId"]);
                $Topic->Delete();
            }
            # delete record from database
            $this->DB->Query("DELETE FROM Forums WHERE ForumId = ".$this->ForumId);
        }
    }
    /*@}*/

    /** @name Accessors */
    /*@{*/

    /**
     * Get the forum's Id
     * @return forum Id
     */
    function ForumId()          {  return $this->ForumId;  }

    /**
     * Get the date of the most recent post
     * @return Post date or "None" for empty forums
     */
    function LastMessageDate()
    {
        $Message = $this->GetLastMessage();
        if (isset($Message))
            return $Message->DatePosted()." by ";
        else
            return "None";
    }

    /**
     * Get the CWIS username of the most recent poster
     * @return The CWIS username of the most recent poster
     */
    function LastMessagePoster()
    {
        $Message = $this->GetLastMessage();
        if (isset($Message))
            return $Message->PosterName();
    }

    /**
     * Get the email address of the most recent poster
     * @return email address of the most recent poster
     */
    function LastMessagePosterEmail()
    {
        $Message = $this->GetLastMessage();
        if (isset($Message))
            return $Message->PosterEmail();
    }

    /**
     * Get the CWIS username of the forum's moderator
     * @return CWIS username of the forum's moderator
     */
    function ModeratorName()
    {
        $ModeratorName = new User($this->DB, (int)$this->ModeratorId());
        return $ModeratorName->Get("UserName");
    }

    /**
     * Get the email of the forum's moderator
     * @return email of the forum's modreator
     */
    function ModeratorEmail()
    {
        $ModeratorName = new User($this->DB, (int)$this->ModeratorId());
        return $ModeratorName->Get("EMail");
    }

    /**
     * Get a list of the topics in this forum
     * @return an array of TopicId's for this forum's conversations
     */
    function GetTopicList()
    {
        $Topics = array();

        $this->DB->Query("Select * from Topics where ForumId = ".
                    $this->ForumId." ORDER BY DateCreated Desc");

        # get list of topics for this forum
        while ($Entry = $this->DB->FetchRow())
        {
            $Topics[$Entry["TopicId"]] = new Topic($Entry["TopicId"]);
        }
        return $Topics;
    }

    /**
     * Get the last message posted in the forum.
     * @return a Message object of the last posted message or NULL if empty
     */
    function GetLastMessage()
    {
        $Message = NULL;

        $this->DB->Query("
            SELECT M.* FROM Messages M
            LEFT JOIN Topics T
            ON M.ParentId = T.TopicId
            WHERE M.ParentType = ".addslashes(Message::PARENTTYPE_TOPIC)."
            AND T.ForumId = '".addslashes($this->ForumId)."'
            ORDER BY DatePosted DESC
            LIMIT 1");

        if ($this->DB->NumRowsSelected())
        {
            $Row = $this->DB->FetchRow();
            $Message = new Message($Row["MessageId"]);
        }

        return $Message;
    }

    /**
     * Get or modify the forum's name
     * @param NewValue (OPTIONAL)
     * @return forum name
     */
   function ForumName($NewValue = DB_NOVALUE) {  return $this->UpdateValue("ForumName", $NewValue);  }

   /**
    * Get or modify the forum description
    * @param NewValue (OPTIONAL)
    * @return forum description
    */
   function ForumDescription($NewValue = DB_NOVALUE) {  return $this->UpdateValue("ForumDescription", $NewValue);  }

   /**
    * Get or set the forum's topic count
    * @param NewValue (OPTIONAL)
    * @return topic count
    */
   function TopicCount($NewValue = DB_NOVALUE) {  return $this->UpdateValue("TopicCount", $NewValue);  }

   /**
    * Get or set the forum's message count
    * @param NewValue (OPTIONAL)
    * @return message count
    */
   function MessageCount($NewValue = DB_NOVALUE) {  return $this->UpdateValue("MessageCount", $NewValue);  }

   /**
    * Get or set the forum's moderator
    * @param NewValue (OPTIONAL)
    * @return the CWIS user ID of the forum's moderator
    */
   function ModeratorId($NewValue = DB_NOVALUE) {  return $this->UpdateValue("ModeratorId", $NewValue);  }

   /**
    * Retrieve error codes associated with the creation of the forum.
    * @return Forum::OK if everything worked, something else otherwise.
    */
   function GetErrorStatus() { return $this->ErrorStatus; }

   /*@}*/

    # ---- PRIVATE INTERFACE -------------------------------------------------

   private $ForumId;
   private $DB;
   private $DBFields;
   private $ErrorStatus;

   # convenience function to supply parameters to Database->UpdateValue()
   private function UpdateValue($FieldName, $NewValue)
   {
       if ($this->ErrorStatus==Forum::OK)
       {
           return $this->DB->UpdateValue("Forums", $FieldName, $NewValue,
                                         "ForumId = '".$this->ForumId."'", $this->DBFields, TRUE);
       }
       else
       {
           return NULL;
       }
   }
}
