<?PHP
#
#   FILE:  EditMessageTemplate.php (Mailer plugin)
#
#   Copyright 2012 Edward Almasy and Internet Scout
#   http://scout.wisc.edu
#

# check that user should be on this page
CheckAuthorization(PRIV_COLLECTIONADMIN, PRIV_SYSADMIN);

# load up current templates
$Plugin = $GLOBALS["G_PluginManager"]->GetPluginForCurrentPage();
$G_Templates = $Plugin->ConfigSetting("Templates");

# take action based on which button was pushed or which action was requested
$Action = isset($_POST["Submit"]) ? $_POST["Submit"]
        : (isset($_GET["AC"]) ? $_GET["AC"] : NULL);
$Id = isset($_POST["F_Id"]) ? $_POST["F_Id"]
        : (isset($_GET["ID"]) ? $_GET["ID"] : NULL);
switch ($Action)
{
    case "Add Template":
        # set up blank template
        $G_Id = "NEW";
        $G_Name = "";
        $G_From = "X-PORTALNAME-X <X-ADMINEMAIL-X>";
        $G_Subject = "";
        $G_Body = "";
        $G_ItemBody = "";
        $G_Headers = "";

        # set flag to display template editing form
        $G_DisplayMode = "Adding";
        break;

    case "Edit":
    case "Delete":
        # load specified template
        $G_Id = $Id;
        $G_Name = $G_Templates[$Id]["Name"];
        $G_From = $G_Templates[$Id]["From"];
        $G_Subject = $G_Templates[$Id]["Subject"];
        $G_Body = $G_Templates[$Id]["Body"];
        $G_ItemBody = $G_Templates[$Id]["ItemBody"];
        $G_Headers = $G_Templates[$Id]["Headers"];

        # set flag to display editing or deletion confirmation as appropriate
        $G_DisplayMode = ($Action == "Edit") ? "Editing" : "Confirm";
        break;

    case "Confirm":
        # delete template
        unset($G_Templates[$Id]);
        $Plugin->ConfigSetting("Templates", $G_Templates);

        # set flag to display template list
        $G_DisplayMode = "Listing";
        break;

    case "Save":
        # if new template
        if ($Id == "NEW")
        {
            # get next template ID
            $Id = (($G_Templates === NULL) || !count($G_Templates)) ? 0
                    : (max(array_keys($G_Templates)) + 1);
        }

        # save template
        $G_Templates[$Id] = array(
                "Name" => $_POST["F_Name"],
                "From" => $_POST["F_From"],
                "Subject" => $_POST["F_Subject"],
                "Body" => StripXSSThreats($_POST["F_Body"]),
                "ItemBody" => StripXSSThreats($_POST["F_ItemBody"]),
                "Headers" => $_POST["F_Headers"],
                );
        $Plugin->ConfigSetting("Templates", $G_Templates);

        # set flag to display template list
        $G_DisplayMode = "Listing";
        break;

    case "Cancel":
    default:
        # set flag to display template list
        $G_DisplayMode = "Listing";
        break;
}

