<?PHP
#
#   FILE:  UpdateTopic.php
#
#   Part of the Collection Workflow Integration System (CWIS)
#   Copyright 2012-2013 Edward Almasy and Internet Scout Research Group
#   http://scout.wisc.edu/cwis/
#

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

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

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

    # Return to home page
    $_SESSION["Message"]    = $Message;
    $_SESSION["F_Subject"]  = $F_Subject;
    $_SESSION["F_Body"]     = $F_Body;
    $_SESSION["ParentId"]   = $ParentId;
    $_SESSION["ResourceId"] = $ResourceId;
    $_SESSION["IsUpdate"]   = $IsUpdate;

    if ($IsUpdate)
    {
        global $MessageId;
        $_SESSION["MessageId"] = $MessageId;
        if (isset($ForumId))
        {
            $_SESSION["ForumId"] = $ForumId;
        }
    }

    # 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["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 $ForumId;
    global $ParentId;
    global $F_TopicName;
    global $F_Subject;
    global $F_Body;
    global $Message;

    $_SESSION["Message"]     = $Message;
    $_SESSION["F_Subject"]   = $F_Subject;
    $_SESSION["F_Body"]      = $F_Body;
    $_SESSION["F_TopicName"] = $F_TopicName;
    $_SESSION["ForumId"]     = $ForumId;
    $_SESSION["ParentId"]    = $ParentId;

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

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

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

            $_SESSION["ForumId"] = $ParentId;
            $AF->SetJumpToPage("ForumTopics");
        }
        else
        {
            print("<pre>No such topic</pre>");
        }
    }
}

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

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

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

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

# delete message
function DeleteMessage()
{
    global $MessageId, $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();
                    $AF->SetJumpToPage("index.php?P=TopicMessages"
                                       ."&TopicId=".$TopicId
                                       ."&ForumId=".$ForumId);
                }
                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()
{
    # 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, $ParentType;

    $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)
        {
            $Message->Body($F_Body);
            $Message->Subject($F_Subject);
            $Message->DateEdited(date("YmdHis"));
            $Message->EditorId($User->Id());

            if ($ParentType==1)
            {
                $AF->SetJumpToPage("index.php?P=TopicMessages"
                                   ."&ForumId=".$ForumId
                                   ."&TopicId=".$ParentId);
            }
            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)
        {
            $ErrorMessages []= "Error: One or more missing values. ".
                "Make sure all values are filled in.";
            $Target = "index.php?P=PostMessage"
                ."&TopicId=".$ParentId ;
        }
        # resource comment
        else
        {
            $ErrorMessages []= "Error: You must enter a comment";
            $Target = "index.php?P=AddResourceComment"
                ."&ResourceId=".$ParentId;
        }

        $_SESSION["ErrorMessages"] = $ErrorMessages;
        $_SESSION["F_Subject"]     = $F_Subject;
        $_SESSION["F_Body"]        = $F_Body;
        $_SESSION["F_TopicName"]   = $F_TopicName;

        $Target .= "&ForumId=".$ForumId;
        $Target .= "&MessageId=".$MessageId;

        $AF->SetJumpToPage($Target);
    }
}

# add list value
function AddNewTopic()
{
    global $User, $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.";
        $Target = "index.php?P=AddTopic";

        $_SESSION["ErrorMessages"] = $ErrorMessages;
        $_SESSION["F_Subject"]     = $F_Subject;
        $_SESSION["F_Body"]        = $F_Body;
        $_SESSION["F_TopicName"]   = $F_TopicName;

        $Target .= "&ForumId=".$ForumId;
        $Target .= "&ParentId=".$ParentId;
        $AF->SetJumpToPage($Target);
    }
}
# 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 $F_Subject, $F_Body, $ParentId, $ForumId, $AF;
    global $ParentType, $MessageId;

    $_SESSION["F_Subject"] = $F_Subject;
    $_SESSION["F_Body"]    = $F_Body;

    if ($ParentType == 1)
    {
        $Target = "index.php?P=PostMessage";
        $Target .= "&ForumId=".$ForumId;
        $Target .= "&TopicId=".$ParentId;

        if (isset($MessageId))
        {
            $Target .= "&MessageId=".$MessageId;
        }
    }
        # resource comment
    else
    {
        $Target = "index.php?P=AddResourceComment";
        $Target .= "&ResourceId=".$ParentId;
    }

    $AF->SetJumpToPage($Target);
}

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

    $Target = "index.php?P=EditTopic";
    $Target .= "&ForumId=".$ForumId;
    $Target .= "&TopicId=".$ParentId;

    $_SESSION["F_TopicName"] = $F_TopicName;

    $AF->SetJumpToPage($Target);
}

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

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

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

    $Target = "index.php?P=TopicMessages";

    $Target .= "&ForumId=".$Topic->ForumId() ;
    $Target .= "&TopicId=".$ParentId ;

    $AF->SetJumpToPage($Target);
}

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

    $Target = "index.php?P=AddTopic";

    $Target .= "&ForumId=".$ForumId;
    $Target .= "&TopicId=".$ParentId;

    $_SESSION["F_TopicName"] = $F_TopicName;
    $_SESSION["F_Subject"]   = $F_Subject;
    $_SESSION["F_Body"]      = $F_Body;

    $AF->SetJumpToPage($Target);
}

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

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

    $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);

                $Target = "index.php?P=TopicMessages";

                $Target .= "&ForumId=".$ForumId;
                $Target .= "&TopicId=".$ParentId;

                $AF->SetJumpToPage($Target);
            }
            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("index.php?P=FullRecord&ID=".$ParentId);
        }
    }
    # 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";
        }

        if ($ParentType==1)
        {
            $Target = "index.php?P=PostMessage".
                "&ForumId=".$ForumId.
                "&TopicId=".$ParentId;
            $_SESSION["F_TopicName"]   = $F_TopicName;
        }
        else
        {
            $Target =
                "index.php?P=AddResourceComment".
                "&ResourceId=".$ParentId;
        }

        $_SESSION["ErrorMessages"] = $ErrorMessages;
        $_SESSION["F_Subject"]     = $F_Subject;
        $_SESSION["F_Body"]        = $F_Body;

        $AF->SetJumpToPage($Target);
    }
}

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

    $DB = new Database();

    # 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["ErrorMessage"] = $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);
        }
    }
}

function GetFromSession($VarName){
    $Value = NULL;
    if (isset($_SESSION[$VarName]))
    {
        $Value = $_SESSION[$VarName];
        unset ($_SESSION[$VarName]);
    }
    return $Value;
}

# ----- 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 $PosterId;

if (isset($_POST["ResourceId"]))
    $ResourceId = $_POST["ResourceId"];
else if (isset($_SESSION["ResourceId"]))
    $ResourceId = GetFromSession("ResourceId");

if (isset($_POST["PosterId"]))
    $PosterId = $_POST["PosterId"];
else if (isset($_SESSION["PosterId"]))
    $PosterId = GetFromSession("PosterId");

if (isset($_GET["ForumId"]))
    $ForumId = $_GET["ForumId"];
else if (isset($_POST["ForumId"]))
    $ForumId = $_POST["ForumId"];
else if (isset($_SESSION["ForumId"]))
    $ForumId = GetFromSession("ForumId");

if (isset($_GET["TopicId"]))
    $ParentId = $_GET["TopicId"];
else if (isset($_POST["TopicId"]))
    $ParentId = $_POST["TopicId"];
else if (isset($_SESSION["TopicId"]))
    $ParentId = GetFromSession("TopicId");
else if (isset($_POST["ParentId"]))
    $ParentId = $_POST["ParentId"];

# check for ParentId from Resource
if (is_null($ParentId))
    $ParentId = GetFromSession("ParentId");

if (isset($_POST["F_Subject"]))
    $F_Subject = $_POST["F_Subject"];
else if (isset($_GET["F_Subject"]))
    $F_Subject = $_GET["F_Subject"];
else if (isset($_SESSION["F_Subject"]))
    $F_Subject = GetFromSession("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 (isset($_SESSION["F_Body"]))
    $F_Body = GetFromSession("F_Body");

if (isset($_POST["F_TopicName"]))
    $F_TopicName = $_POST["F_TopicName"];
else if (isset($_SESSION["F_TopicName"]))
    $F_TopicName = GetFromSession("F_TopicName");

if (isset($_GET["MessageId"]))
    $MessageId = $_GET["MessageId"];
else if ( isset($_POST["MessageId"]) )
    $MessageId = $_POST["MessageId"];
else if (isset($_SESSION["MessageId"]))
    $MessageId = GetFromSession("MessageId");

if (isset($_GET["message"]))
    $message = $_GET["message"];
else if (isset($_SESSION["message"]))
    $message = GetFromSession("message");

if (isset($_SESSION["ErrorMessages"]))
    $ErrorMessages = GetFromSession("ErrorMessages");

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 ".
        " this function.";

    if (isset($ResourceId))
    {
        $AF->SetJumpToPage("index.php?P=FullRecord&ID=".$ParentId);
    }
    else
    {
        $Target = "index.php?P=PostMessage";

        $Target .= "&TopicId=".$ParentId;
        $Target .= "&MessageId=".$MessageId;
        $Target .= "&ForumId=".$ForumId;

        $_SESSION["ErrorMessages"] = $ErrorMessages;
        $_SESSION["F_Subject"]     = $F_Subject;
        $_SESSION["F_Body"]        = $F_Body;
        $_SESSION["F_TopicName"]   = $F_TopicName;

        $AF->SetJumpToPage($Target);
    }
}

# 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")
{
    if (isset($ResourceId))
        PreviewComment(TRUE);
    else
        PreviewNewTopic();
}
# 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
    {
        $Target = "index.php?P=ConfirmDeleteTopic";
        $Target .= "&ForumId=".$ForumId;
        $Target .= "&TopicId=".$ParentId;
        $AF->SetJumpToPage($Target);
    }
}
# 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();

    $Target = "index.php?P=TopicMessages";

    $Target .= "&ForumId=".$ForumId;
    $Target .= "&TopicId=".$ParentId;

    $AF->SetJumpToPage($Target);
}
else if ( $Submit == "Clean Spam" && isset($_POST["PosterId"]) &&
          intval($_POST["PosterId"]) > 1 )
{
    SlayUser(intval($_POST["PosterId"]));

    if ($ResourceId == -1 )
    {
        $AF->SetJumpToPage("TrackUserComments");
    }

    else
    {
        $AF->SetJumpToPage("index.php?P=FullRecord&ID=".$ResourceId);
    }
}
else
{
    # else Cancel, fall through
    if (isset($ResourceId))
    {
       if ($ResourceId == -1)
       {
           $AF->SetJumpToPage("TrackUserComments");
       }
       else
       {
           $AF->SetJumpToPage("index.php?P=FullRecord&ID=".$ResourceId);
       }
    }
    else
    {
        if (isset($Message))
        {
            $Target = "index.php?P=TopicMessages";
            $Target .= "&ForumId=".$ForumId;
            $Target .= "&TopicId=".$ParentId;
            $AF->SetJumpToPage($Target);
        }
        else
        {
            $Target = "index.php?P=ForumTopics";
            $Target .= "&ForumId=".$ForumId;
            $AF->SetJumpToPage($Target);
        }
    }
}
