<?PHP
#
#   FILE:  PreferencesComplete.php
#
#   Copyright 2011 Internet Scout Project
#   http://scout.wisc.edu
#

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

global $ErrorMessages;
global $SuccessMessages;

# check if user is logged in and if the submit button was pressed
if ($User->IsLoggedIn() == FALSE || !isset($_POST["Submit"]))
{
    $AF->SetJumpToPage("Home");
}

# strings that trigger saving
$SaveStrings = array(
    # the expected save string
    "Save Changes",
    # backwards compatibility strings
    "Save New Settings",
    "Change User Information");

if (in_array($_POST["Submit"], $SaveStrings))
{
    # update password
    if (strlen($_POST["F_NewPassword"]) > 0)
    {
        # attempt to change password
        $Status = $User->ChangePassword(
            $_POST["F_OldPassword"],
            $_POST["F_NewPassword"],
            $_POST["F_NewPasswordAgain"]);

        # if password change was unsuccessful
        if ($Status != U_OKAY)
        {
            # add to error list
            $ErrorMessages[] = $User->StatusMessage();
        }
        else
        {
            # isn't an error message, but lets the user know the password was
            # changed
            $SuccessMessages[] = "The password was successfully changed.";

            # signal password change
            $AF->SignalEvent("EVENT_USER_PASSWORD_CHANGED", array(
                    "UserId" => $User->Id(),
                    "OldPassword" => $_POST["F_OldPassword"],
                    "NewPassword" => $_POST["F_NewPassword"]));
        }
    }

    # set new active UI
    if (isset($_POST["F_ActiveUI"]))
    {
        $User->Set("ActiveUI", $_POST["F_ActiveUI"]);
    }

    # set search results per page
    if (isset($_POST["F_SearchResultsPerPage"]))
    {
        $SearchResultsPerPage = intval($_POST["F_SearchResultsPerPage"]);

        if (!in_array($SearchResultsPerPage, array(5, 10, 20, 30, 50, 100)))
        {
            $SearchResultsPerPage = 5;
        }

        $User->Set("RecordsPerPage", $SearchResultsPerPage);
    }

    # if record was found
    if ($User->Status() == U_OKAY)
    {
        # save new user settings
        $User->Set("RealName", isset($_POST["F_RealName"]) ? $_POST["F_RealName"] : "");
        $User->Set("WebSite", isset($_POST["F_WebSite"]) ? $_POST["F_WebSite"] : "");
        $User->Set("AddressLineOne", isset($_POST["F_AddressLineOne"]) ? $_POST["F_AddressLineOne"] : "");
        $User->Set("AddressLineTwo", isset($_POST["F_AddressLineTwo"]) ? $_POST["F_AddressLineTwo"] : "");
        $User->Set("City", isset($_POST["F_City"]) ? $_POST["F_City"] : "");
        $User->Set("State", isset($_POST["F_State"]) ? $_POST["F_State"] : "");
        $User->Set("ZipCode", isset($_POST["F_ZipCode"]) ? $_POST["F_ZipCode"] : "");
        $User->Set("Country", isset($_POST["F_Country"]) ? $_POST["F_Country"] : "");

        if (isset($_POST["F_EMail"]))
        {
            $NewEmail = $_POST["F_EMail"];
            $OldEmail = $User->Get("EMail");
            if ($NewEmail != $OldEmail)
            {
                if (User::IsValidLookingEmailAddress($NewEmail))
                {
                    $User->Set("EMailNew", $NewEmail);

                    # send confirmation e-mail
                    $ActivationUrlParameters = "?UN=".urlencode($User->Get("UserName"))
                        ."&AC=".$User->GetMailChangeCode();
                    $ActivationUrl = "http://".$_SERVER["SERVER_NAME"]
                        .dirname($_SERVER["SCRIPT_NAME"])
                        ."/index.php".$ActivationUrlParameters."&P=ActivateAccount";
                    $ManualActivationUrl = "http://".$_SERVER["SERVER_NAME"]
                        .dirname($_SERVER["SCRIPT_NAME"])
                        ."/index.php?P=ManuallyActivateAccount";
                    $OurSubstitutions = array(
                        "X-PORTALNAME-X" => $SysConfig->PortalName(),
                        "X-CHANGEURL-X" => $ActivationUrl,
                        "X-CHANGEPARAMETERS-X" => $ActivationUrlParameters,
                        "X-MANUALCHANGEURL-X" => $ManualActivationUrl,
                        "X-NEWEMAILADDRESS-X" => $NewEmail,
                        );
                    $MailTemplate = $SysConfig->MailChangeMailSubject()."\n"
                        .$SysConfig->MailChangeMailBody();
                    $FromAddress = $SysConfig->PortalName()." <".$SysConfig->AdminEmail().">";
                    $User->SendEMail($MailTemplate, $FromAddress, $OurSubstitutions, $NewEmail);

                    $SuccessMessages []= "A confirmation message has been sent to the "
                        ."new email address that you specified. Click the link it contains "
                        ."to complete your address change.";
                }
                else
                {
                    $ErrorMessages []= "Invalid Email";
                }
            }
        }
    }
    else
    {
        # put up error message
        $ErrorMessages []= "Your information could not be modified. Please contact the webmaster.";
    }
}

# cancel
else if ($_POST["Submit"] == "Cancel")
{
    $AF->SetJumpToPage("Home");
}

# make error list persistent if errors were found
if (isset($ErrorMessages))
{
    $Session->PassVariable("ErrorMessages");
}

if (isset($SuccessMessages))
{
    $Session->PassVariable("SuccessMessages");
}

$AF->SetJumpToPage("Preferences");
