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

if (!CheckAuthorization(PRIV_SYSADMIN, PRIV_POSTCOMMENTS)) {  return;  }

global $AF, $G_User;

# Don't accept resource comments from spambots:
if ($GLOBALS["G_PluginManager"]->PluginEnabled("BotDetector") &&
    $GLOBALS["G_PluginManager"]->GetPlugin("BotDetector")->CheckForSpamBot())
{
    $AF->SetJumpToPage("UnauthorizedAccess");
    return;
}

if (!isset($_GET["RI"]) || !isset($_POST["F_Body"]) ||
    !isset($_POST["F_Submit"]))
{
    $AF->SetJumpToPage("UnauthorizedAccess");
    return;
}

$ResourceId = intval($_GET["RI"]);

$F_Body   = $_POST["F_Body"];
$F_Submit = $_POST["F_Submit"];

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

# Default JumpTo Page, possibly modified later.
$DestinationUrl = "index.php?P=FullRecord&ID=".$ResourceId ;

if ($F_Submit == "Add Comment")
{
    $Resource = new Resource($ResourceId);

    if ($Resource->Status() == 1 &&
        strlen($F_Body) && $CommentStatus[0] !== FALSE)
    {
        $Message = new Message();
        $Message->ParentId($ResourceId);
        $Message->ParentType( Message::PARENTTYPE_RESOURCE);
        $Message->DatePosted(date("YmdHis"));
        $Message->PosterId($G_User->Id() );
        $Message->Subject( "Comment On: ".$Resource->GetMapped("Title") );
        $Message->Body($F_Body);
    }
}
else if ($F_Submit == "Update Comment")
{
    $Message = new Message(intval($_GET["MI"]));

    if ($Message->GetErrorStatus() == Message::OK &&
        ($User->Id() == $Message->PosterId() || $User->HasPriv(PRIV_SYSADMIN)) &&
        strlen($F_Body) && $CommentStatus[0] !== FALSE )
    {
        $Message->Body($F_Body);
        $Message->DateEdited(date("YmdHis"));
        $Message->EditorId($G_User->Id());
    }
}
else if ($F_Submit == "Delete Comment" && isset($_GET["MI"]) )
{
    $Message = new Message( intval($_GET["MI"]) );
    if ($Message->GetErrorStatus() == Message::OK) {
        $Message->Delete(); }
}
else if ($F_Submit == "Preview" || $F_Submit == "Edit Comment")
{
    $_SESSION["Body"] = $F_Body;
    if ($F_Submit == "Preview") {
        $DestinationUrl = "index.php?P=PreviewComment&RI=".$ResourceId ; }
    else {
        $DestinationUrl = "index.php?P=AddResourceComment&RI=".$ResourceId; }
}

$AF->SetJumpToPage( $DestinationUrl );
