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

# ----- MAIN -----------------------------------------------------------------

# check if current user is authorized
if (!CheckAuthorization(PRIV_SYSADMIN)) {  return;  }

# get the required global variables
global $AF, $G_SysConfig;

# prepare an error list in case we have to return to the previous page
$H_ErrorMessages = new ErrorList();

$Schema = new MetadataSchema(MetadataSchema::SCHEMAID_DEFAULT);

# if save changes was requested
if ($_POST["Submit"] != "Cancel")
{
    # save new portal name
    $G_SysConfig->PortalName($_POST["F_PortalName"]);

    # if new administrator e-mail is valid
    $F_AdminEmail = trim($_POST["F_AdminEmail"]);
    if (preg_match("/[a-z0-9.\!%-_]+@[a-z0-9.-]+\.[a-z]+/i", $F_AdminEmail))
    {
        # save new administrator e-mail address
        $G_SysConfig->AdminEmail($F_AdminEmail);
    }
    else
    {
        # add error message to error list
        $H_ErrorMessages->AddMessage(
                "The administrator e-mail address you entered contained illegal"
                . "characters or otherwise appeared to be invalid.");
        $_SESSION["F_AdminEmail"] = $F_AdminEmail;
    }

    # save legal notice
    $G_SysConfig->LegalNotice($_POST["F_LegalNotice"]);

    # save new search engine keywords
    if (isset($_POST["F_SiteKeywords"]))
    {
        $G_SysConfig->SiteKeywords($_POST["F_SiteKeywords"]);
    }

    # save new about text
    if (isset($_POST["F_AboutText"]))
    {
        $G_SysConfig->AboutText($_POST["F_AboutText"]);
    }

    # save new announcements setting
    $G_SysConfig->AnnouncementsEnabled(
            ($_POST["F_AnnouncementsEnabled"] == "1") ? 1 : 0);

    # save new forums settings
    $G_SysConfig->ForumsEnabled(($_POST["F_ForumsEnabled"] == "1") ? 1 : 0);

     # save new saved search mailing setting
    $G_SysConfig->UserAgentsEnabled(
            ($_POST["F_UserAgentsEnabled"] == "1") ? 1 : 0);

    # save new resource ratings setting
    $G_SysConfig->ResourceRatingsEnabled(
            ($_POST["F_ResourceRatingsEnabled"] == "1") ? 1 : 0);

    # And be sure that the Cumulative rating field is enabled
    if ($G_SysConfig->ResourceRatingsEnabled())
    {
        $Field = $Schema->GetFieldByName("Cumulative Rating");
        $Field->Enabled(TRUE);
    }

    # save new resource comments setting
    $G_SysConfig->ResourceCommentsEnabled(
            ($_POST["F_ResourceCommentsEnabled"] == "1") ? 1 : 0);

    # save new incremental keyword search setting
    $G_SysConfig->IncrementalKeywordSearchEnabled(
            ($_POST["F_IncrementalKeywordSearchEnabled"] == "1") ? 1 : 0);

    # save new OAI-SQ setting
    $G_SysConfig->OAISQEnabled(
            ($_POST["F_OAISQEnabled"] == "1") ? 1 : 0);

    # if new number of announcements on home page is valid
    $F_NumAnnounceOnHomePage =
        intval(trim($_POST["F_NumAnnounceOnHomePage"]));
    if (($F_NumAnnounceOnHomePage >= 1) && ($F_NumAnnounceOnHomePage <= 99))
    {
        # save new number of announcements on home page
        $G_SysConfig->NumAnnounceOnHomePage($F_NumAnnounceOnHomePage);
    }
    else
    {
        # add error message to error list
        $H_ErrorMessages->AddMessage(
                "The maximum number of announcements on the home page was "
                . "invalid.  This value must be at least 1 and less than 100.");
        $_SESSION["F_NumAnnounceOnHomePage"] = $F_NumAnnounceOnHomePage;
    }

    # if new number of announcements on home page is valid
    $F_NumResourcesOnHomePage =
        intval(trim($_POST["F_NumResourcesOnHomePage"]));
    if (($F_NumResourcesOnHomePage >= 1) && ($F_NumResourcesOnHomePage <= 99))
    {
        # save new number of announcements on home page
        $G_SysConfig->NumResourcesOnHomePage($F_NumResourcesOnHomePage);
    }
    else
    {
        # add error message to error list
        $H_ErrorMessages->AddMessage(
                "The maximum number of resources on the home page was invalid. "
                . "This value must be at least 1 and less than 100.");
        $_SESSION["F_NumResourcesOnHomePage"] = $F_NumResourcesOnHomePage;
    }

    # save new show resource count setting
    $G_SysConfig->ShowNumResourcesEnabled(
            ($_POST["F_ShowNumResourcesEnabled"] == "1") ? 1 : 0);

    # save new active user interface setting
    $G_SysConfig->DefaultActiveUI($_POST["F_DefaultActiveUI"]);

    # set all users to default active user interface if requested
    if (isset($_POST["F_SetAllUsersToDefaultActiveUI"]))
    {
        $DB = new Database();
        $DB->Query("UPDATE APUsers SET ActiveUI = '"
                .addslashes($_POST["F_DefaultActiveUI"])."'");
    }

    # save new current user interface theme setting
    if (isset($_POST["F_CurrentTheme"]))
    {
        $G_SysConfig->CurrentTheme($_POST["F_CurrentTheme"]);
    }

    # save new allow multiple UIs setting
    $G_SysConfig->AllowMultipleUIsEnabled(
            ($_POST["F_AllowMultipleUIsEnabled"] == "1") ? 1 : 0);

    # save new resource launches new window setting
    $G_SysConfig->ResourceLaunchesNewWindowEnabled(
            ($_POST["F_ResourceLaunchesNewWindowEnabled"] == "1") ? 1 : 0);

    # show group names in full record page
    $G_SysConfig->ShowGroupNamesEnabled(
            ($_POST["F_ShowGroupNamesEnabled"] == "1") ? 1 : 0);

    # save resource field mappings
    $G_SysConfig->TitleField(
        $_POST["F_TitleField"] ? $_POST["F_TitleField"] : NULL);
    $G_SysConfig->DescriptionField(
        $_POST["F_DescriptionField"] ? $_POST["F_DescriptionField"] : NULL);
    $G_SysConfig->UrlField(
        $_POST["F_UrlField"] ? $_POST["F_UrlField"] : NULL);
    $G_SysConfig->Value("FileField",
        $_POST["F_FileField"] ? $_POST["F_FileField"] : NULL);
    $G_SysConfig->ScreenshotField(
        $_POST["F_ScreenshotField"] ? $_POST["F_ScreenshotField"] : NULL);

    # save new link settings
    $G_SysConfig->Value("PreferredLinkValue", $_POST["F_PreferredLinkValue"]);
    $G_SysConfig->Value("TitlesLinkTo", $_POST["F_TitlesLinkTo"]);

    # save new collapes metadata field groups setting
    $G_SysConfig->Value("CollapseMetadataFieldGroups",
            GetArrayValue($_POST, "F_CollapseMetadataFieldGroups"), 0);

    # save new require email with feedback setting
    $G_SysConfig->Value("RequireEmailWithFeedback",
            GetArrayValue($_POST, "F_RequireEmailWithFeedback"), 0);

    # save new forum interface settings
    $G_SysConfig->ForumsAllowHTML(
            ($_POST["F_ForumsAllowHTML"] == "1") ? 1 : 0);
    $G_SysConfig->ForumsUseWYSIWYG(
            ($_POST["F_ForumsUseWYSIWYG"] == "1") ? 1 : 0 );

    # if new number of classifications per browse page is valid
    $F_NumClassesPerBrowsePage =
        intval(trim($_POST["F_NumClassesPerBrowsePage"]));
    if (($F_NumClassesPerBrowsePage >= 4) && ($F_NumClassesPerBrowsePage <= 999))
    {
        # save new number of classifications per browse page
        $G_SysConfig->NumClassesPerBrowsePage($F_NumClassesPerBrowsePage);
    }
    else
    {
        # add error message to error list
        $H_ErrorMessages->AddMessage(
                "The number of classifications per page for browsing was "
                . "invalid. There must be at least 4 classifications per page.");
        $Session->PassVariable("F_NumClassesPerBrowsePage");
    }

    # if new number of columns per browse page is valid
    $F_NumColumnsPerBrowsePage =
        intval(trim($_POST["F_NumColumnsPerBrowsePage"]));
    if (($F_NumColumnsPerBrowsePage >= 1) && ($F_NumColumnsPerBrowsePage <= 4))
    {
        # save new number of columns per browse page
        $G_SysConfig->NumColumnsPerBrowsePage($F_NumColumnsPerBrowsePage);
    }
    else
    {
        # add error message to error list
        $H_ErrorMessages->AddMessage(
                "The number of columns per page for browsing was invalid. "
                . "There must be at least 1 and less than 5 columns per page.");
        $_SESSION["F_NumColumnsPerBrowsePage"] = $F_NumColumnsPerBrowsePage;
    }

    # default classification tree
    if (isset($_POST["F_BrowsingFieldId"]))
    {
        $Field = $Schema->GetField($_POST["F_BrowsingFieldId"]);

        if ($Field->Type() == MetadataSchema::MDFTYPE_TREE)
        {
            $G_SysConfig->BrowsingFieldId($_POST["F_BrowsingFieldId"]);
        }
    }

    # save new search term handling setting
    $G_SysConfig->SearchTermsRequired(
            ($_POST["F_SearchTermHandling"] == "AND") ? 1 : 0);

    # save always display advanced search limits setting
    $G_SysConfig->DisplayLimitsByDefault(
            ($_POST["F_DisplayLimitsByDefault"] == "1") ? 1 : 0);

    # if new number of announcements on home page is valid
    $F_DefaultRecordsPerPage = intval($_POST["F_DefaultRecordsPerPage"]);
    if (in_array($F_DefaultRecordsPerPage, array(5, 10, 20, 30, 50, 100)))
    {
        # save new number of announcements on home page
        $G_SysConfig->DefaultRecordsPerPage($F_DefaultRecordsPerPage);
    }
    else
    {
        # add error message to error list
        $H_ErrorMessages->AddMessage(
                "The default number of search results per page was invalid.");
        $_SESSION["F_DefaultRecordsPerPage"] = $F_DefaultRecordsPerPage;
    }

    # save new max facets per field setting
    $G_SysConfig->MaxFacetsPerField( intval($_POST["F_MaxFacetsPerField"]) );

    # save new default sort field setting
    if (isset($_POST["F_DefaultSortField"]))
    {
        $G_SysConfig->DefaultSortField(intval($_POST["F_DefaultSortField"]));
    }
    else
    {
        $G_SysConfig->DefaultSortField(NULL);
    }

    # save new traffic analyzer settings
    $G_SysConfig->AddAWStatsScript(
            ($_POST["F_AddAWStatsScript"] == "1") ? 1 : 0);

    # save new max tasks setting
    if (isset($_POST["F_MaxTasks"]))
    {
        $AF->MaxTasks(max(1, $_POST["F_MaxTasks"]));
    }

    # save new engine update priority settings
    $G_SysConfig->Value("SearchEngineUpdatePriority",
            GetArrayValue($_POST, "F_SearchEngineUpdatePriority"), 3);
    $G_SysConfig->Value("RecommenderEngineUpdatePriority",
            GetArrayValue($_POST, "F_RecommenderEngineUpdatePriority"), 3);

    # save new saved search mail template setting
    if (isset($_POST["F_SavedSearchMailTemplate"]))
    {
        $G_SysConfig->SavedSearchMailTemplate($_POST["F_SavedSearchMailTemplate"]);
    }

    # set default privs for new users
    if (isset($_POST["F_DefaultUserPrivs"]))
    {
        $G_SysConfig->DefaultUserPrivs($_POST["F_DefaultUserPrivs"]);
    }
    else
    {
        $G_SysConfig->DefaultUserPrivs(array());
    }

    # save new secure login setting
    if (isset($_POST["F_SecureLogin"]))
    {
        $G_SysConfig->SecureLogin(intval($_POST["F_SecureLogin"]));
    }

    # clear page cache in case any of our changes impact page generation
    $AF->ClearPageCache();
}

# if errors were found
if (isset($H_ErrorMessages) && $H_ErrorMessages->HasErrors())
{
    # return to editing page with error messages
    $_SESSION["H_ErrorMessages"] = serialize($H_ErrorMessages);
    $AF->SetJumpToPage("EditSysConfig");
}
else
{
    # go to sys admin page
    $AF->SetJumpToPage("SysAdmin");
}
