<?PHP
#
#   FILE:  PreferencesComplete.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 -----------------------------------------------------------------

global $ErrorMessages;
global $SuccessMessages;
global $G_User;

# check if user is logged in and if the submit button was pressed
if ($G_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 = $G_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[] = $G_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" => $G_User->Id(),
                    "OldPassword" => $_POST["F_OldPassword"],
                    "NewPassword" => $_POST["F_NewPassword"]));
        }
    }

    # set new active UI
    if (isset($_POST["F_ActiveUI"]))
    {
        $G_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;
        }

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

    # if record was found
    if ($G_User->Status() == U_OKAY)
    {
        $UEUI = new UserEditingUI($G_User);
        # save new user settings
        $UEUI->UpdateUserAttributes($_POST);
        $Errors = $UEUI->UpdateUserFields(CWUser::GetCustomUserFields());

        # add field error messages
        foreach ($Errors as $Error)
        {
            $ErrorMessages[] = "The ".$Error." field must not be empty.";
        }

        $UEUI->UploadImages($_POST, $_FILES);
        $UEUI->UploadFiles($_POST, $_FILES);

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

                    $Protocol = isset($_SERVER["HTTPS"]) ? "https://" : "http://";

                    # send confirmation e-mail
                    $ActivationUrlParameters = "?UN=".urlencode($G_User->Get("UserName"))
                        ."&AC=".$G_User->GetMailChangeCode();
                    $ActivationUrl = $Protocol.$_SERVER["SERVER_NAME"]
                        .dirname($_SERVER["SCRIPT_NAME"])
                        ."/index.php".$ActivationUrlParameters."&P=ActivateAccount";
                    $ManualActivationUrl = $Protocol.$_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().">";
                    $G_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.";
    }
}

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

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

$AF->SetJumpToPage("Preferences");
