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

# make sure user has needed privileges
$Plugin = $GLOBALS["G_PluginManager"]->GetPluginForCurrentPage();
$NeededPrivileges = array($Plugin->ConfigSetting("PrivilegeToEdit"));
$PFactory = new Pages_PageFactory();
if (isset($_GET["ID"]) && $PFactory->ItemExists($_GET["ID"]))
{
    $Page = new Pages_Page($_GET["ID"]);
    if ($GLOBALS["G_User"]->IsLoggedIn()
            && ($GLOBALS["G_User"]->Id() == $Page->AuthorId()))
    {
        $NeededPrivileges[] = $Plugin->ConfigSetting("PrivilegeToAuthor");
    }
}
elseif (isset($_GET["ID"]) && ($_GET["ID"] == "NEW"))
{
    $NeededPrivileges[] = $Plugin->ConfigSetting("PrivilegeToAuthor");
}
if (!CheckAuthorization($NeededPrivileges)) {  return;  }

# save invoking page
$H_ReturnTo = isset($_POST["F_ReturnTo"]) ? $_POST["F_ReturnTo"]
        : (isset($_GET["ReturnTo"]) ? $_GET["ReturnTo"]
        : (isset($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"]
        : NULL));

# take action based on which button was pushed or which action was requested
$Action = isset($_POST["Submit"]) ? $_POST["Submit"] : "Edit";
$H_Id = isset($_POST["F_Id"]) ? $_POST["F_Id"]
        : (isset($_GET["ID"]) ? $_GET["ID"] : NULL);
switch ($Action)
{
    case "Edit":
        # if new page was requested
        if ($H_Id == "NEW")
        {
            # initialize blank page values
            $H_PageTitle = "";
            $H_PageContent = "";
            $H_Id = "NEW";
            $H_CleanUrl = "";
            $H_Privileges = array();

            # set display mode to adding new page
            $H_DisplayMode = "Adding";
        }
        else
        {
            # if page was not specified
            if ($H_Id === NULL)
            {
                # set error message to be displayed
                $H_ErrorMsgs[] = "No page ID was specified.";
                $H_DisplayMode = "Error";
            }
            else
            {
                # if page does not exist
                if (!$PFactory->ItemExists($H_Id))
                {
                    # set error message to be displayed
                    $H_ErrorMsgs[] = "The specified page (ID=<i>"
                            .$H_Id."</i>) does not exist.";
                    $H_DisplayMode = "Error";
                }
                else
                {
                    # retrieve values for page
                    $Page = new Pages_Page($H_Id);
                    $H_PageTitle = $Page->Title();
                    $H_PageContent = $Page->Content();
                    $H_CleanUrl = $Page->CleanUrl();

                    # load privileges for page
                    $H_Privileges = $Page->Privileges();

                    # set display mode to editing existing page
                    $H_DisplayMode = "Editing";
                }
            }
        }
        break;

    case "Add":
    case "Save":
        # tidy up clean URL if specified
        $CleanUrl = "";
        if (array_key_exists("F_CleanUrl", $_POST)
                && strlen(trim($_POST["F_CleanUrl"])))
        {
            $CleanUrl = $_POST["F_CleanUrl"];
            $CleanUrl = trim($CleanUrl, "/");
            $CleanUrl = str_replace($GLOBALS["AF"]->BaseUrl(), "", $CleanUrl);
            $CleanUrl = preg_replace("%[^a-z0-9_/-]+%i", "", $CleanUrl);
        }

        # if specified clean URL is already in use (and not by us)
        $CleanUrlList = $PFactory->GetCleanUrls();
        if (strlen($CleanUrl) && $GLOBALS["AF"]->CleanUrlIsMapped($CleanUrl)
                && (!array_key_exists($H_Id, $CleanUrlList)
                        || ($CleanUrl != $CleanUrlList[$H_Id])))
        {
            # set error message to be displayed
            $H_ErrorMsgs[] = "The specified clean URL path (<a href=\""
                    .$GLOBALS["AF"]->BaseUrl().$CleanUrl."\"><i>".$CleanUrl
                    ."</i></a>) is already in use.";

            # reload values for editing
            $H_PageTitle = $_POST["F_PageTitle"];
            $H_PageContent = $_POST["F_PageContent"];
            $H_CleanUrl = $CleanUrl;
            $H_Privileges = array_key_exists("F_Privileges", $_POST)
                    ? $_POST["F_Privileges"] : array();

            # set display mode appropriately
            $H_DisplayMode = ($H_Id == "NEW") ? "Adding" : "Editing";
        }
        else
        {
            # if this is a new page
            if ($H_Id == "NEW")
            {
                # add new page to database
                $ItemValues = array(
                        "PageContent" => $_POST["F_PageContent"],
                        "CleanUrl" => $CleanUrl,
                        "AuthorId" => $GLOBALS["G_User"]->Id(),
                        );
                $H_Id = $PFactory->AddItem($_POST["F_PageTitle"], $ItemValues);
                $Page = new Pages_Page($H_Id);
                $Page->UpdatedOn($Page->CreatedOn());
            }
            else
            {
                # update values for page in database
                $Page = new Pages_Page($H_Id);
                $Page->Title($_POST["F_PageTitle"]);
                $Page->Content($_POST["F_PageContent"]);
                $Page->CleanUrl($CleanUrl);
                $Page->EditorId($GLOBALS["G_User"]->Id());
                $Page->UpdatedOn(date("Y-m-d H:i:s"));
            }
            $Page->Privileges(array_key_exists("F_Privileges", $_POST)
                    ? $_POST["F_Privileges"] : array());

            # go to display saved page
            if (strlen($CleanUrl))
            {
                $GLOBALS["AF"]->SetJumpToPage($CleanUrl, TRUE);
            }
            else
            {
                $GLOBALS["AF"]->SetJumpToPage(
                        "index.php?P=P_Pages_DisplayPage&amp;ID=".$H_Id);
            }
        }
        break;

    case "Cancel":
        # return to invoking page
        $GLOBALS["AF"]->SetJumpToPage($H_ReturnTo);
        break;
}


