<?PHP
#
#   FILE:  UpdateTopic.php
#
#   FUNCTIONS PROVIDED:
#
#   FUNCTIONS EXPECTED:
#
#   Part of the Scout Portal Toolkit
#   Copyright 2004 Internet Scout Project
#   http://scout.cs.wisc.edu
#

# ----- EXPORTED FUNCTIONS ---------------------------------------------------

# ----- LOCAL FUNCTIONS ------------------------------------------------------

# preview new comment
function PreviewComment($IsUpdate=False)
{
    global $AF;
    global $Session;
    global $ParentId;
    global $F_Subject;
    global $F_Body;
    global $Message;
    global $ResourceId;

    # remove unwanted html tags
    $F_Body = StripXSSThreats($F_Body);

    # return to home page
    $Session->PassVariable("Message", $Message);
    $Session->PassVariable("F_Subject", $F_Subject);
    $Session->PassVariable("F_Body", $F_Body);
    $Session->PassVariable("ParentId", $ParentId);
    $Session->PassVariable("ResourceId", $ResourceId);
    $Session->PassVariable("IsUpdate", $IsUpdate);

    if ($IsUpdate)
    {
        global $MessageId;
        $Session->PassVariable("MessageId", $MessageId);
    }

    # make sure a comment has been entered
    if (strlen($F_Body))
        $AF->SetJumpToPage("PreviewComment");
    # tell user to enter a comment
    else
    {
        $ErrorMessages[] = "Error: You must enter a comment.";
        $Session->PassVariable("ErrorMessages",$ErrorMessages);
        $AF->SetJumpToPage("AddResourceComment");
    }

    # Signal the validate event on preview so that things like the Captcha
    # plugin can record successful validation and not ask again.
    $AF->SignalEvent("EVENT_VALIDATE_USER_COMMENT", array($F_Subject, $F_Body));
}

# preview post
function PreviewNewTopic()
{
    global $AF;
    global $Session;
    global $ForumId;
    global $ParentId;
    global $F_TopicName;
    global $F_Subject;
    global $F_Body;
    global $Message;

    # return to home page
    $Session->PassVariable("Message", $Message);
    $Session->PassVariable("F_Subject", $F_Subject);
    $Session->PassVariable("F_Body", $F_Body);
    $Session->PassVariable("F_TopicName", $F_TopicName);
    $Session->PassVariable("ForumId", $ForumId);
    $Session->PassVariable("ParentId", $ParentId);
    $AF->SetJumpToPage("PreviewMessage");
}

# delete topic and messages
function DeleteTopic()
{
    global $Session, $AF;
    global $ParentId;

    if (!empty($ParentId))
    {
        $Topic = new Topic($ParentId);
        if ($Topic->GetErrorStatus() == Topic::OK)
        {
            $Topic->Delete();

            $Session->PassVariable("ForumId", $ParentId);
            $AF->SetJumpToPage("ForumTopics");
        }
        else
        {
            print("<pre>No such topic</pre>");
        }
    }
}

# delete comment
function DeleteComment()
{
    global $Session, $ParentId, $MessageId, $AF;

    if (isset($MessageId))
    {
        $Message = new Message($MessageId);

        if ($Message->GetErrorStatus() == Message::OK)
        {
            $Message->Delete();
        }
        else
        {
            print("<pre>No such message</pre>");
        }

        # doesn't use session variables because they are problematic with page
        # refreshes and when using the back button when clicking a link
        #$Session->PassVariable("ResourceId", $ParentId);
        #$AF->SetJumpToPage("FullRecord");

        $AF->SetJumpToPage("index.php?P=FullRecord&ID=".$ParentId);
    }
}

# delete message
function DeleteMessage()
{
    global $MessageId, $Session, $AF;

    if (isset($MessageId))
    {
        $Message = new Message($MessageId);

        if ($Message->GetErrorStatus() == Message::OK)
        {
            $TopicId = $Message->ParentId();
            $Topic = new Topic($TopicId);
            if ($Topic->GetErrorStatus() == Topic::OK)
            {
                $ForumId = $Topic->ForumId();
                $Forum = new Forum($ForumId);
                if ($Forum->GetErrorStatus() == Forum::OK)
                {
                    # update count for topic and forum and delete message
                    $MessageCount = $Topic->MessageCount();
                    $Topic->MessageCount($MessageCount - 1);

                    $MessageCount = $Forum->MessageCount();
                    $Forum->MessageCount($MessageCount - 1);

                    $Message->Delete();

                    $Session->PassVariable("TopicId", $TopicId );
                    $Session->PassVariable("ForumId", $ForumId );
                    $AF->SetJumpToPage("TopicMessages");
                }
                else
                {
                    print("<pre>No such forum</pre>");
                }
            }
            else
            {
                print("<pre>No such topic</pre>");
            }
        }
        else
        {
            print("<pre>No such message</pre>");
        }
    }
}

# update comment
# comments are treated much like messages, except ParentId = 2
function UpdateComment()
{
    global $Session, $ParentId, $AF;

    # overload UpdateMessage to deal with comments as well
    UpdateMessage();
}

# update message
function UpdateMessage()
{
    global $User, $MessageId, $F_Subject, $F_Body, $ForumId, $ParentId, $AF;
    global $F_TopicName, $Session, $ParentType;

    # remove unwanted html tags
    $F_Subject = StripXSSThreats($F_Subject);
    $F_Body    = StripXSSThreats($F_Body);


    $CommentStatus = $AF->SignalEvent("EVENT_VALIDATE_USER_COMMENT", array($F_Subject, $F_Body));

    # update the post
    if (strlen($F_Subject) && strlen($F_Body) && isset($MessageId) &&
        $CommentStatus[0] !== FALSE)
    {
        $Message = new Message($MessageId);
        if ($Message->GetErrorStatus() == Message::OK)
        {

            # add info that message was edited
            $F_Body .= "\n\n<br><br><small>This message edited by ".
                $User->Get("UserName").
                " on ".date("F j, Y \a\\t g:i a")."</small>";

            $Message->Body($F_Body);
            $Message->Subject($F_Subject);
            $Message->DatePosted(date("YmdHis"));

            if ($ParentType==1)
            {
                $Session->PassVariable("ForumId", $ForumId);
                $Session->PassVariable("TopicId", $ParentId);
                $AF->SetJumpToPage("TopicMessages");
            }
            else
            {
                $AF->SetJumpToPage("index.php?P=FullRecord&ID=".$ParentId);
            }
        }
        else
        {
            print("<pre>No such message</pre>");
        }
    }
    else
    {
        if ($CommentStatus[0]===FALSE)
        {
            $ErrorMessages []= $CommentStatus[1];
        }

        # normal formum message
        if ($ParentType == 1)
        {
            $Session->PassVariable("TopicId", $ParentId);
            $ErrorMessages []= "Error: One or more missing values. ".
                "Make sure all values are filled in.";
            $Target = "index.php?P=PostMessage&amp;MessageId=".$MessageId;
        }
        # resource comment
        else
        {
            $Session->PassVariable("ResourceId", $ParentId);
            $ErrorMessages []= "Error: You must enter a comment";
            $Target = "index.php?P=AddResourceComment";
        }

        $Session->PassVariable("ErrorMessages",$ErrorMessages);
        $Session->PassVariable("F_Subject", $F_Subject);
        $Session->PassVariable("F_Body", $F_Body);
        $Session->PassVariable("F_TopicName", $F_TopicName);
        $Session->PassVariable("ForumId", $ForumId);
        $Session->PassVariable("MessageId", $MessageId);
        $AF->SetJumpToPage($Target);
    }
}

# add list value
function AddNewTopic()
{
    global $User, $Session, $F_TopicName, $ForumId, $F_Subject, $F_Body, $AF;
    global $ParentId, $ParentType;

    $UserId = $User->Get("UserId");

    # remove unwanted html tags
    $F_TopicName = StripXSSThreats($F_TopicName);

    # check for required fields
    if (strlen($F_TopicName) && strlen($F_Subject) && strlen($F_Body))
    {
        $Topic = new Topic();
        $Forum = new Forum($ForumId);
        if ($Forum->GetErrorStatus() == Forum::OK)
        {
            $ParentId = $Topic->TopicId();
            $Topic->TopicName($F_TopicName);
            $Topic->DateCreated(date("YmdHis"));
            $Topic->ForumId($ForumId);
            $Topic->ViewCount("0");
            $Topic->MessageCount("0");
            $Topic->CreatorId($UserId);

            $TopicCount = $Forum->TopicCount();
            $Forum->TopicCount($TopicCount + 1);

            # Now Post the message
            $ParentType = 1;
            PostMessage();
        }
        else
        {
            print("<pre>No such forum</pre>");
        }
    }
    # missing values
    else
    {
        $ErrorMessages[] = "Error: One or more missing values. ".
            "Make sure all values are filled in.";
        $Session->PassVariable("ErrorMessages",$ErrorMessages);
        $Session->PassVariable("F_Subject", $F_Subject);
        $Session->PassVariable("F_Body", $F_Body);
        $Session->PassVariable("F_TopicName", $F_TopicName);
        $Session->PassVariable("ForumId", $ForumId);
        $Session->PassVariable("ParentId", $ParentId);
        $AF->SetJumpToPage("AddTopic");
    }
}
# comments are treated much like messages, except ParentId = 2
function AddComment()
{
    global $ParentId, $AF;

    # overload PostMessage to deal with comments as well
    PostMessage();
}

function EditMessage()
{
    global $Session, $F_Subject, $F_Body, $ParentId, $ForumId, $AF;
    global $ParentType;

    $Session->PassVariable("F_Subject", $F_Subject);
    $Session->PassVariable("F_Body", $F_Body);

    if ($ParentType == 1)
    {
        $Session->PassVariable("TopicId", $ParentId);
        $Target = "index.php?P=PostMessage.php&amp;MessageId=".$MessageId;
    }
        # resource comment
    else
    {
        $Session->PassVariable("ResourceId", $ParentId);
        $Target = "index.php?P=AddResourceComment";
    }

    $AF->SetJumpToPage($Target);
}

function EditTopic()
{
    global $Session, $F_TopicName, $ParentId, $ForumId, $AF;

    $Session->PassVariable("ForumId", $ForumId);
    $Session->PassVariable("TopicId", $ParentId);
    $Session->PassVariable("F_TopicName", $F_TopicName);

    $AF->SetJumpToPage("EditTopic");
}

function UpdateTopic()
{
    global $F_TopicName, $ParentId, $Session, $AF ;

    # remove unwanted html tags
    $F_TopicName = StripXSSThreats($F_TopicName);

    $Topic = new Topic($ParentId);
    $Topic->TopicName($F_TopicName);

    $Session->PassVariable("ForumId", $Topic->ForumId() );
    $Session->PassVariable("TopicId", $ParentId);
    $AF->SetJumpToPage("TopicMessages");
}

function EditTopicAndMessage()
{
    global $Session, $F_Subject, $F_Body, $ParentId, $ForumId, $AF;
    global $F_TopicName;

    $Session->PassVariable("ForumId", $ForumId);
    $Session->PassVariable("TopicId", $ParentId);
    $Session->PassVariable("F_TopicName", $F_TopicName);
    $Session->PassVariable("F_Subject", $F_Subject);
    $Session->PassVariable("F_Body", $F_Body);

    $AF->SetJumpToPage("AddTopic");
}

function PostMessage()
{
    global $User, $Session, $F_Subject, $F_Body, $ParentId, $ForumId, $AF;
    global $ParentType, $F_TopicName;

    # PosterId is the user
    $PosterId = $User->Get("UserId");

    # remove unwanted html tags
    $F_Subject = StripXSSThreats($F_Subject);
    $F_Body = StripXSSThreats($F_Body);

    $CommentStatus = $AF->SignalEvent("EVENT_VALIDATE_USER_COMMENT", array($F_Subject, $F_Body));

    # We have a subject, we have a body,
    # and either no captcha was displayed (Status is null),
    # Or the captcha was solved successfully (Status is true).
    if (strlen($F_Subject) && strlen($F_Body) &&
        $CommentStatus[0] !== FALSE )
    {
        if ($ParentType == 1)
        {
            $Forum = new Forum($ForumId);
            $Topic = new Topic($ParentId);
            if ($Forum->GetErrorStatus() == Forum::OK &&
                $Topic->GetErrorStatus() == Topic::OK)
            {
                # If the selected topic and forum exist
                $Message = new Message();
                $Message->ParentId($ParentId);
                $Message->ParentType($ParentType);
                $Message->DatePosted(date("YmdHis"));
                $Message->PosterId($PosterId);
                $Message->Subject($F_Subject);
                $Message->Body($F_Body);

                # update counts for topic and forum
                $MessageCount = $Forum->MessageCount();
                $Forum->MessageCount($MessageCount + 1);

                $MessageCount = $Topic->MessageCount();
                $Topic->MessageCount($MessageCount + 1);

                $Session->PassVariable("ForumId", $ForumId);
                $Session->PassVariable("TopicId", $ParentId);
                $AF->SetJumpToPage("TopicMessages");
            }
            else
            {
                print("<pre>No such topic or forum</pre>");
            }
        }
        else
        {
            $Message = new Message();
            $Message->ParentId($ParentId);
            $Message->ParentType($ParentType);
            $Message->DatePosted(date("YmdHis"));
            $Message->PosterId($PosterId);
            $Message->Subject($F_Subject);
            $Message->Body($F_Body);

            $AF->SetJumpToPage("FullRecord");
        }
    }
    # report errors
    else
    {
        if ($CommentStatus[0]===FALSE)
        {
            $ErrorMessages []= $CommentStatus[1];
        }

        if ( !(strlen($F_Subject) && strlen($F_Body)) )
        {
            $ErrorMessages []=
                ($ParentType==1)?
                "Error: One or more missing values. ".
                "Make sure all values are filled in.":
                "Error: You must enter a comment";
        }

        $Target = ($ParentType==1)?
            "index.php?P=PostMessage":
            "index.php?P=AddResourceComment";

        $Session->PassVariable("ErrorMessages",$ErrorMessages);
        $Session->PassVariable("F_Subject", $F_Subject);
        $Session->PassVariable("F_Body", $F_Body);
        $Session->PassVariable("F_TopicName", $F_TopicName);
        $Session->PassVariable("ForumId", $ForumId);
        $Session->PassVariable("TopicId", $ParentId);
        $AF->SetJumpToPage($Target);
    }
}

# remove posting privilege for message poster
function RemovePostPrivilege()
{
    global $User;
    global $Session;
    global $MessageId;
    global $ErrorMessages;

    $DB = new SPTDatabase();

    # recheck user privileges to perform this operation
    if ($User->HasPriv(PRIV_FORUMADMIN) &&
        $User->HasPriv(PRIV_USERADMIN) &&
        isset($MessageId))
    {
        # get this message
        $Message = new Message($MessageId);

        if ($Message->GetErrorStatus() === Message::OK)
        {

            # get poster
            $Poster = new SPTUser((int)$Message->PosterId());

            if ($Poster->Status() === U_OKAY)
            {
                # revoke their posting privileges
                $Poster->RevokePriv(PRIV_POSTTOFORUMS);
                $ErrorMessages[] = "Posting privilege removed for User \"".
                    $Poster->Get("UserName")."\".";
            }
            else
            {
                $ErrorMessages[]= "Could not find UserId=".
                    $Message->PosterId();
            }
        }
        else
        {
            $ErrorMessages[]= "Could not find MessageId=".$MessageId;
        }
    }
    else
    {
        $ErrorMessages[] = "You don't have sufficient privileges to "
            ."modify a user";
    }

    $Session->PassVariable("ErrorMessages", $ErrorMessages);
}

function SlayUser($PosterId)
{
    global $DB, $User;

    if ($User->HasPriv(PRIV_FORUMADMIN, PRIV_USERADMIN))
    {
        $Poster = new SPTUser($PosterId);
        if ($Poster->Status() == U_OKAY )
        {
            $Poster->RevokePriv(PRIV_POSTTOFORUMS);
            $Poster->RevokePriv(PRIV_POSTCOMMENTS);
            $Poster->GrantPriv(PRIV_USERDISABLED);

            $DB->Query("DELETE FROM Messages WHERE "
                       ."PosterId = ".$PosterId);
        }
        else
        {
            print("<pre>");
            print("Failed to revoke posting privs, error follows:\n");
            print($Poster->StatusMessage( $Poster->Status()));
            print("</pre>");
            exit(1);
        }
    }
}

# ----- MAIN -----------------------------------------------------------------

# non-standard global variables
global $ErrorMessages;
global $F_Body;
global $F_Subject;
global $F_TopicName;
global $ForumId;
global $Message;
global $MessageId;
global $ParentId;
global $ParentType;
global $ResourceId;
global $MessageId;

if (isset($_POST["ResourceId"]))
    $ResourceId = $_POST["ResourceId"];
else if ($Session->IsRegistered("ResourceId"))
    $ResourceId = $Session->Get("ResourceId");

if (isset($_GET["ForumId"]))
    $ForumId = $_GET["ForumId"];
else if (isset($_POST["ForumId"]))
    $ForumId = $_POST["ForumId"];
else if ($Session->IsRegistered("ForumId"))
    $ForumId = $Session->Get("ForumId");

if (isset($_GET["TopicId"]))
    $ParentId = $_GET["TopicId"];
else if (isset($_POST["TopicId"]))
    $ParentId = $_POST["TopicId"];
else if ($Session->IsRegistered("TopicId"))
    $ParentId = $Session->Get("TopicId");

# check for ParentId from Resource
if (is_null($ParentId))
    $ParentId = $Session->Get("ParentId");

if (isset($_POST["F_Subject"]))
    $F_Subject = $_POST["F_Subject"];
else if (isset($_GET["F_Subject"]))
    $F_Subject = $_GET["F_Subject"];
else if ($Session->IsRegistered("F_Subject"))
    $F_Subject = $Session->Get("F_Subject");

if (isset($_POST["F_Body"]))
    $F_Body = $_POST["F_Body"];
else if (isset($_GET["F_Body"]))
    $F_Body = $_GET["F_Body"];
else if ($Session->IsRegistered("F_Body"))
    $F_Body = $Session->Get("F_Body");

if (isset($_POST["F_TopicName"]))
    $F_TopicName = $_POST["F_TopicName"];
else if ($Session->IsRegistered("F_TopicName"))
    $F_TopicName = $Session->Get("F_TopicName");

if (isset($_GET["MessageId"]))
    $MessageId = $_GET["MessageId"];
else if ( isset($_POST["MessageId"]) )
    $MessageId = $_POST["MessageId"];
else if ($Session->IsRegistered("MessageId"))
    $MessageId = $Session->Get("MessageId");

if (isset($_GET["message"]))
    $message = $_GET["message"];
else if ($Session->IsRegistered("message"))
    $message = $Session->Get("message");

if (isset($_POST["Submit"]))
    $Submit = $_POST["Submit"];
else
    $Submit = $_GET["Submit"];

if (isset($_POST["OkayToDelete"]))
    $OkayToDelete = $_POST["OkayToDelete"];
else
    $OkayToDelete = FALSE;

# echo "ForumId=$ForumId, TopicId=$TopicId, MessageId=$MessageId<br>";
# echo "Submit=$Submit, F_Body=$F_Body, ParentId=$ParentId<br>";

# don't allow any operation if user is not logged in
if ($User->IsLoggedIn() == FALSE)
{
    $ErrorMessages[] = "Error: User must be logged in to perform ".
        "perform this function.";

    if (isset($ResourceId))
    {
        # doesn't use session variables because they are problematic with page
        # refreshes and when using the back button when clicking a link
        #$Session->PassVariable("ResourceId", $ParentId);
        #$AF->SetJumpToPage("FullRecord");

        $AF->SetJumpToPage("index.php?P=FullRecord&ID=".$ParentId);
    }
    else
    {
        $Session->PassVariable("ErrorMessages",$ErrorMessages);
        $Session->PassVariable("F_Subject", $F_Subject);
        $Session->PassVariable("F_Body", $F_Body);
        $Session->PassVariable("F_TopicName", $F_TopicName);
        $Session->PassVariable("ForumId", $ForumId);
        $Session->PassVariable("TopicId", $ParentId);
        $Session->PassVariable("MessageId", $MessageId);
        $AF->SetJumpToPage("PostMessage");
    }
}

# this variable determines if we are coming from a message screen or not
if (isset($message))
    $Message = 1;

# comments are type 2, messages are type 1
if ($Submit == "Add Comment")
{
    $ParentType = 2;
    AddComment();
}
# add new topic & message
else if (substr($Submit, 0, 3) == "Add")
{
    AddNewTopic();
}
# update just the topic
else if ($Submit == "Update Topic")
{
    UpdateTopic();
}
# edit existing topic
else if ($Submit == "Edit Topic")
{
    EditTopic();
}
# post new comment
else if ($Submit == "Post New Comment")
{
    $ParentType = 2;
    AddComment();
}
# just post a new message
else if (substr($Submit, 0, 4) == "Post")
{
    $ParentType = 1;
    PostMessage();
}
# edit a new message from preview
else if ($Submit == "Edit Message")
{
    $ParentType = 1;
    EditMessage();
}
else if ($Submit == "Edit Comment")
{
   $ParentType = 2;
   EditMessage();
}
# edit a new topic and message from preview
else if ($Submit == "Edit Topic and Message")
{
    $ParentType = 1;
    EditTopicAndMessage();
}
# update a comment
else if ($Submit == "Update Comment")
{
    $ParentType = 2;
    UpdateComment();
}
# update an edited message
else if (substr($Submit, 0, 6) == "Update")
{
    $ParentType = 1;
    UpdateMessage();
}
else if ($Submit == "Preview Update")
{
    PreviewComment(True);
}
# preview new topic and message, or preview comment
else if ($Submit == "Preview")
{
    if (isset($ResourceId))
        PreviewComment();
    else
        PreviewNewTopic();
}
# remove Topic from forum
else if ($Submit == "Delete Topic")
{
    if ($OkayToDelete)
    {
        DeleteTopic();
    }
    # give user a second chance
    else
    {
        $Session->PassVariable("ForumId", $ForumId);
        $Session->PassVariable("TopicId", $ParentId);
        $AF->SetJumpToPage("ConfirmDeleteTopic");
    }
}
# preview new topic and message
else if ($Submit == "Delete Comment")
{
    $ParentType = 2;
    DeleteComment();
}
# delete a message
else if ($Submit == "Delete Message")
{
    $ParentType = 1;
    DeleteMessage();
}
# delete a message
else if ($Submit == "Remove Post Privilege")
{
    $ParentType = 1;
    RemovePostPrivilege();
    $Session->PassVariable("ForumId", $ForumId);
    $Session->PassVariable("TopicId", $ParentId);
    $AF->SetJumpToPage("TopicMessages");
}
else if ( $Submit == "Clean Spam" && isset($_POST["PosterId"]) &&
          intval($_POST["PosterId"])>1 )
{
    SlayUser(intval($_POST["PosterId"]));
    if ($ResourceId == -1 ) {
        $AF->SetJumpToPage("TrackUserComments");
    }
    else
    {
        # doesn't use session variables because they are problematic with page
        # refreshes and when using the back button when clicking a link
        #$Session->PassVariable("ResourceId", $ParentId);
        #$AF->SetJumpToPage("FullRecord");

        $AF->SetJumpToPage("index.php?P=FullRecord&ID=".$ParentId);
    }
}
else
{
    # else Cancel, fall through
    if (isset($ResourceId))
    {
       if ($ResourceId == -1)
       {
           $AF->SetJumpToPage("TrackUserComments");
       }
       else
       {
           # doesn't use session variables because they are problematic with page
           # refreshes and when using the back button when clicking a link
           #$Session->PassVariable("ResourceId", $ParentId);
           #$AF->SetJumpToPage("FullRecord");

           $AF->SetJumpToPage("index.php?P=FullRecord&ID=".$ParentId);
       }
    }
    else
    {
        # return to home page
        $Session->PassVariable("ForumId", $ForumId);
        if (isset($ParentId))
            $Session->PassVariable("TopicId", $ParentId);

        if (isset($Message))
        {
            $Session->PassVariable("ForumId", $ForumId);
            $Session->PassVariable("TopicId", $ParentId);
            $AF->SetJumpToPage("TopicMessages");
        }
        else
        {
            $Session->PassVariable("ForumId", $ForumId);
            $AF->SetJumpToPage("ForumTopics");
        }
    }
}

?>
