<?PHP
#
#   FILE:  EditSysConfigComplete.php
#
#   Part of the Collection Workflow Integration System (CWIS)
#   Copyright 2011 Internet Scout Project
#   http://scout.wisc.edu/
#

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

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

global $ErrorMessages;
$ErrorMessages = new ErrorList();
$Schema = new MetadataSchema();

# if save changes was requested
if ($_POST["Submit"] != "Cancel")
{
    # 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
        $SysConfig->AdminEmail($F_AdminEmail);
    }
    else
    {
        # add error message to error list
        $ErrorMessages->AddMessage(
                "The administrator e-mail address you entered contained illegal characters or otherwise appeared to be invalid.");
        $Session->PassVariable("F_AdminEmail");
    }

    # save new portal name
    $SysConfig->PortalName($_POST["F_PortalName"]);

    # 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
        $SysConfig->NumClassesPerBrowsePage($F_NumClassesPerBrowsePage);
    }
    else
    {
        # add error message to error list
        $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
        $SysConfig->NumColumnsPerBrowsePage($F_NumColumnsPerBrowsePage);
    }
    else
    {
        # add error message to error list
        $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->PassVariable("F_NumColumnsPerBrowsePage");
    }

    # 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
        $SysConfig->NumAnnounceOnHomePage($F_NumAnnounceOnHomePage);
    }
    else
    {
        # add error message to error list
        $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->PassVariable("F_NumAnnounceOnHomePage");
    }

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

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

    # 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
        $SysConfig->NumResourcesOnHomePage($F_NumResourcesOnHomePage);
    }
    else
    {
        # add error message to error list
        $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->PassVariable("F_NumResourcesOnHomePage");
    }

    # 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
        $SysConfig->DefaultRecordsPerPage($F_DefaultRecordsPerPage);
    }
    else
    {
        # add error message to error list
        $ErrorMessages->AddMessage(
                "The default number of search results per page was invalid.");
        $Session->PassVariable("F_DefaultRecordsPerPage");
    }

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

    # save new active user interface setting
    $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"]) )
        $SysConfig->CurrentTheme($_POST["F_CurrentTheme"]);

    # save new default character coding setting
    $SysConfig->DefaultCharacterSet($_POST["F_DefaultCharacterSet"]);

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

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

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

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

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

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

     # save new search user agents setting
    $SysConfig->UserAgentsEnabled(($_POST["F_UserAgentsEnabled"] == "1") ? 1 : 0);

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

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

    # save new accessibility wizard setting
    $SysConfig->AccessibilityWizardEnabled(
                            ($_POST["F_AccessibilityWizardEnabled"] == "1") ? 1 : 0);

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

    # save new traffic analyzer settings
    $SysConfig->AddAWStatsScript(
                            ($_POST["F_AddAWStatsScript"] == "1") ? 1 : 0);
    $SysConfig->AddGoogleAnalytics(
                            ($_POST["F_AddGoogleAnalytics"] == "1") ? 1 : 0);
    $SysConfig->GoogleAnalyticsCode($_POST["F_GoogleAnalyticsCode"]);

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

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

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

    # save resource field mappings
    $SysConfig->TitleField(
        $_POST["F_TitleField"] ? $_POST["F_TitleField"] : NULL);
    $SysConfig->DescriptionField(
        $_POST["F_DescriptionField"] ? $_POST["F_DescriptionField"] : NULL);
    $SysConfig->UrlField(
        $_POST["F_UrlField"] ? $_POST["F_UrlField"] : NULL);
    $SysConfig->ScreenshotField(
        $_POST["F_ScreenshotField"] ? $_POST["F_ScreenshotField"] : NULL);
    $SysConfig->Value("FileField",
        $_POST["F_FileField"] ? $_POST["F_FileField"] : NULL);
    $SysConfig->Value("PreferredLinkValue", $_POST["F_PreferredLinkValue"]);
    $SysConfig->Value("TitlesLinkTo", $_POST["F_TitlesLinkTo"]);
    $SysConfig->Value("CollapseMetadataFieldGroups", GetArrayValue($_POST, "F_CollapseMetadataFieldGroups"), 0);

    if (isset($_POST["F_SecureLogin"]))
    {
        $SysConfig->SecureLogin(intval($_POST["F_SecureLogin"]));
    }
    if (isset($_POST["F_MaxTasks"]))
    {
        $GLOBALS["AF"]->MaxTasks(max(1, $_POST["F_MaxTasks"]));
    }
    if (isset($_POST["F_MaxExecTime"]))
    {
        $GLOBALS["AF"]->MaxExecutionTime(max(5, $_POST["F_MaxExecTime"]));
    }
    if (isset($_POST["F_CacheInterval"]))
    {
        $GLOBALS["AF"]->TemplateLocationCacheExpirationInterval(
                max(0, $_POST["F_CacheInterval"]));
    }

    if (isset($_POST["F_EmailLineEnding"]))
    {
        $SysConfig->EmailLineEnding($_POST["F_EmailLineEnding"]);
    }

    # set up to test new email delivery settings
    if (isset($_POST["F_MailingMethod"])) {
            Email::DeliveryMethod($_POST["F_MailingMethod"]);  }
    if (isset($_POST["F_SmtpServer"])) {
            Email::Server($_POST["F_SmtpServer"]);  }
    if (isset($_POST["F_SmtpPort"])) {
            Email::Port($_POST["F_SmtpPort"]);  }
    Email::UseAuthentication(isset($_POST["F_SmtpUseAuthentication"]));
    if (isset($_POST["F_SmtpUserName"])) {
            Email::UserName($_POST["F_SmtpUserName"]);  }
    if (isset($_POST["F_SmtpPassword"])
        && $_POST["F_SmtpPassword"] != SystemConfiguration::UNCHANGED_VALUE) {
            Email::Password($_POST["F_SmtpPassword"]);  }

    # if email deliver settings tested out okay
    if (Email::DeliverySettingsOkay())
    {
        # save new delivery settings
        $G_SysConfig->Value("EmailDeliverySettings", Email::DeliverySettings());
    }
    else
    {
        # set error message to be displayed
        $Errs = Email::DeliverySettingErrors();
        if (in_array("UseAuthentication", $Errs)
                || in_array("UserName", $Errs)
                || in_array("Password", $Errs))
        {
            $Msg = "Unable to connect with the specified <b>SMTP User Name</b>"
                    ." and <b>SMTP Password</b>.  Please check that these values"
                    ." are correct to connect to <i>".$_POST["F_SmtpServer"]."</i>.";
        }
        elseif (in_array("Server", $Errs)
                || in_array("Port", $Errs))
        {
            $Msg = "An error was found with the <b>SMTP Server</b> or"
                    ." <b>SMTP Port</b> number.  Please check that these values"
                    ." are correct.";
        }
        elseif (in_array("TLS", $Errs))
        {
            $Msg = "An error was encountered trying to make a TLS connection to"
                    ." the specified server for SMTP.  Please check the server"
                    ." and port values to make sure they are correct.";
        }
        else
        {
            $Msg = "An unknown error was encountered while trying to verify the"
                    ." <i>Mailing</i> settings.";
        }
        $ErrorMessages->AddMessage($Msg);

        # pass new settings back to be corrected
        $Session->PassVariable("F_MailingMethod");
        $Session->PassVariable("F_SmtpServer");
        $Session->PassVariable("F_SmtpPort");
        $Session->PassVariable("F_SmtpUseAuthentication");
        $Session->PassVariable("F_SmtpUserName");
        $Session->PassVariable("F_SmtpPassword");
    }

    # save new logging level
    $GLOBALS["AF"]->LoggingLevel($_POST["F_LoggingLevel"]);

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

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

# if errors were found
if (isset($ErrorMessages) && $ErrorMessages->HasErrors())
{
    # return to editing page with error messages
    $Session->PassVariable("ErrorMessages");
    $AF->SetJumpToPage("EditSysConfig");
}
else
{
    # go to sys admin page
    $AF->SetJumpToPage("SysAdmin");
}
