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

# retrieve ID of page to edit
$PageId = isset($_POST["F_Id"]) ? $_POST["F_Id"]
        : (isset($_GET["ID"]) ? $_GET["ID"] : NULL);

# make sure user has needed privileges
$Plugin = $GLOBALS["G_PluginManager"]->GetPluginForCurrentPage();
$H_SchemaId = $Plugin->ConfigSetting("MetadataSchemaId");
if ($PageId == "NEW")
{
    $Schema = new MetadataSchema($H_SchemaId);
    if (!$Schema->UserCanAuthor($GLOBALS["G_User"]))
    {
        DisplayUnauthorizedAccessPage();
        return;
    }
}
else
{
    $PFactory = new Pages_PageFactory();
    if ($PFactory->ItemExists($PageId))
    {
        $H_Page = new Pages_Page($PageId);
        if (!$H_Page->UserCanEdit($GLOBALS["G_User"]))
        {
            DisplayUnauthorizedAccessPage();
            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";
switch ($Action)
{
    case "Edit":
        # if new page was requested
        if ($PageId == "NEW")
        {
            # create new page
            $H_Page = Pages_Page::Create();

            # set display mode to adding new page
            $H_DisplayMode = "Adding";
        }
        else
        {
            # if page was not specified
            if ($PageId === 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($PageId))
                {
                    # set error message to be displayed
                    $H_ErrorMsgs[] = "The specified page (ID=<i>"
                            .$PageId."</i>) does not exist.";
                    $H_DisplayMode = "Error";
                }
                else
                {
                    # set display mode based on page status
                    $H_DisplayMode = $H_Page->IsTempResource()
                            ? "Adding" : "Editing";
                }
            }
        }

        # load values for editing
        if ($H_DisplayMode != "Error")
        {
            $H_Title = $H_Page->Get("Title");
            $H_Content = $H_Page->Get("Content");
            $H_CleanUrl = $H_Page->Get("Clean URL");
            $H_AltTexts = array();
            $Images = $H_Page->Get("Images", TRUE);
            foreach ($Images as $Image)
            {
                $H_AltTexts[$Image->Id()] = $Image->AltText();
            }
            $H_Privileges = $H_Page->ViewingPrivileges();
            if ($H_Privileges == NULL)
            {
                $H_Privileges = new PrivilegeSet();
            }
        }
        break;

    case "Delete":
        # if image was specified to delete
        $Schema = new MetadataSchema($H_SchemaId);
        if (strlen($_POST["F_ImageToDelete"]))
        {
            # dissociate image from page and delete image
            $Image = new SPTImage($_POST["F_ImageToDelete"]);
            if ($Image->Status() == AI_OKAY)
            {
                $Field = $Schema->GetFieldByName("Images");
                $H_Page->Clear($Field, $Image);
            }
        }
        # if file was specified to delete
        elseif (strlen($_POST["F_FileToDelete"]))
        {
            # dissociate file from page and delete file
            $File = new File($_POST["F_FileToDelete"]);
            if ($File->Status() == File::FILESTAT_OK)
            {
                $Field = $Schema->GetFieldByName("Files");
                $H_Page->Clear($Field, $File);
            }
        }
        break;

    case "Upload":
        # if image uploaded
        if (isset($_FILES["F_Image"]["tmp_name"])
                && is_uploaded_file($_FILES["F_Image"]["tmp_name"]))
        {
            # create temp copy of file with correct name
            $TempFile = "tmp/".$_FILES["F_Image"]["name"];
            copy($_FILES["F_Image"]["tmp_name"], $TempFile);

            # create new Image object from uploaded file
            $Schema = new MetadataSchema($H_SchemaId);
            $Field = $Schema->GetFieldByName("Images");
            $Image = new SPTImage($TempFile,
                                  $Field->MaxWidth(),
                                  $Field->MaxHeight(),
                                  $Field->MaxPreviewWidth(),
                                  $Field->MaxPreviewHeight(),
                                  $Field->MaxThumbnailWidth(),
                                  $Field->MaxThumbnailHeight());

            # if image save succeeded
            if ($Image->Status() == AI_OKAY)
            {
                # attach image to resource
                $H_Page->Set($Field, $Image->Id());

                # set the image's alternate text
                $AltText = GetArrayValue($_POST, "F_ImageAltText");
                if (strlen($AltText)) {  $Image->AltText($AltText);  }
            }
            else
            {
                # set error message and error out
                $ImageName = $_FILES["F_Image"]["name"];
                switch ($Image->Status())
                {
                    case AI_UNKNOWNTYPE:
                        $H_ErrorMsgs[] = "The image file <i>".$ImageName
                                ."</i> uploaded was of an unknown type ("
                                .$Image->Format().").";

                    case AI_UNSUPPORTEDFORMAT:
                        $H_ErrorMsgs[] = "The uploaded image file <i>".$ImageName
                                ."</i> was in an unsupported image format ("
                                .$Image->Format().").";
                        break;

                    default:
                        $H_ErrorMsgs[] = "A problem was encountered uploading"
                                ." the image file <i>".$ImageName."</i>.  ("
                                .$Image->Status().")";
                        break;
                }
            }
        }

        # if file uploaded
        if (isset($_FILES["F_File"]["tmp_name"])
                && is_uploaded_file($_FILES["F_File"]["tmp_name"]))
        {
            # create temp copy of file with correct name
            $TempFile = "tmp/".$_FILES["F_File"]["name"];
            copy($_FILES["F_File"]["tmp_name"], $TempFile);

            # create new File object from uploaded file
            $Schema = new MetadataSchema($H_SchemaId);
            $Field = $Schema->GetFieldByName("Files");
            $FileName = $_FILES["F_File"]["name"];
            $File = new File($TempFile, $H_Page->Id(), $Field->Id(), $FileName);

            # if file save failed
            if ($File->Status() != File::FILESTAT_OK)
            {
                # set error message and error out
                switch ($File->Status())
                {
                    case File::FILESTAT_ZEROLENGTH:
                        $H_ErrorMsgs[] = "The file <i>".$FileName
                                ."</i> uploaded was empty (zero length).";
                        break;

                    default:
                        $H_ErrorMsgs[] = "A problem was encountered uploading"
                                ." the file <i>".$FileName."</i>.  ("
                                .$File->Status().")";
                        break;
                }
            }
        }
        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_Page->Id(), $CleanUrlList)
                        || ($CleanUrl != $CleanUrlList[$H_Page->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_Content"];
            $H_CleanUrl = $CleanUrl;

            # set display mode appropriately
            $H_DisplayMode = $H_Page->IsTempResource() ? "Adding" : "Editing";
        }
        else
        {
            # update page content
            $H_Page->Set("Title", $_POST["F_Title"]);
            $H_Page->Set("Content", $_POST["F_Content"]);
            $H_Page->Set("Clean URL", $CleanUrl);
            foreach ($_POST as $Name => $Value)
            {
                if (preg_match("/^F_ImageAltText_[0-9]+/", $Name))
                {
                    $ImageId = preg_replace("/F_ImageAltText_/", "", $Name);
                    $Image = new SPTImage($ImageId);
                    $Image->AltText($Value);
                }
            }

            # update page modification times
            $H_Page->Set("Last Modified By Id", $GLOBALS["G_User"]->Id());
            $H_Page->Set("Date Last Modified", date("Y-m-d H:i:s"));

            # update viewing privileges for page
            $PrivUI = new PrivilegeEditingUI($H_SchemaId);
            $PrivSets = $PrivUI->GetPrivilegeSetsFromForm();
            $H_Page->ViewingPrivileges($PrivSets["ViewingPrivs"]);

            # set author and mark page no longer temporary if new
            if ($Action == "Add")
            {
                $H_Page->Set("Added By Id", $GLOBALS["G_User"]->Id());
                $H_Page->IsTempResource(FALSE);
            }

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

            # update search indices
            $H_Page->QueueSearchAndRecommenderUpdate();

        }
        break;

    case "Cancel":
        # discard page if temporary
        if (isset($H_Page) && $H_Page->IsTempResource())
        {
            $H_Page->Delete();
        }

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

# if just processed delete or upload request
if (($Action == "Delete") || ($Action == "Upload"))
{
    # retrieve display mode
    $H_DisplayMode = GetArrayValue($_POST, "F_DisplayMode", "Editing");

    # transfer existing values from form
    $H_Title = GetArrayValue($_POST, "F_Title");
    $H_Content = GetArrayValue($_POST, "F_Content");
    $H_CleanUrl = GetArrayValue($_POST, "F_CleanUrl");
    $H_AltTexts = array();
    $Images = $H_Page->Get("Images", TRUE);
    foreach ($Images as $Image)
    {
        if (isset($_POST["F_ImageAltText_".$Image->Id()]))
        {
            $H_AltTexts[$Image->Id()] = $_POST["F_ImageAltText_".$Image->Id()];
        }
        else
        {
            $H_AltTexts[$Image->Id()] = $Image->AltText();
        }
    }

    # transfer viewing privileges for page
    $PrivUI = new PrivilegeEditingUI($H_SchemaId);
    $PrivSets = $PrivUI->GetPrivilegeSetsFromForm();
    $H_Privileges = $PrivSets["ViewingPrivs"];
}
