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

# ----- LOCAL FUNCTIONS ------------------------------------------------------

/**
* Determine if the current user is editing his or her own account.
* @return Returns TRUE if the current user is editing his or her own account and
*      FALSE otherwise.
*/
function IsEditingOwnAccount()
{
    global $User;

    # user is logged in and is not SYSADMIN or USERADMIN
    if ((!$User->HasPriv(PRIV_SYSADMIN) &&
        !$User->HasPriv(PRIV_USERADMIN)) &&
        $User->IsLoggedIn() == TRUE)
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}

/**
* Update the saved searches for a user based on what was submitted in the form.
* @param User $User User whose saved searches should be updated.
*/
function UpdateSavedSearches(User $User)
{
    $SSFactory = new SavedSearchFactory();
    $Searches = $SSFactory->GetSearchesForUser($User->Id());

    # return if the user doesn't have any saved searches
    if (count($Searches) < 0)
    {
        return;
    }

    # get the possible mailing frequency values
    if ($User->HasPriv(PRIV_RESOURCEADMIN))
    {
        $FreqList = SavedSearch::GetSearchFrequencyList();
    }

    else
    {
        $FreqList = SavedSearch::GetSearchFrequencyList(SavedSearch::SEARCHFREQ_HOURLY);
    }

    # update each saved search
    foreach ($Searches as $Search)
    {
        $Frequency = GetArrayValue($_POST, "F_Frequency_".$Search->Id());

        # skip the frequency if it's invalid
        if (!array_key_exists($Frequency, $FreqList))
        {
            continue;
        }

        # update the frequency if given and it has changed
        if (!is_null($Frequency) && $Search->Frequency() != $Frequency)
        {
            $Search->Frequency($Frequency);
        }
    }
}

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

$F_DeleteSavedSearch = GetArrayValue($_POST, "F_DeleteSavedSearch");
$SubmitResult = GetArrayValue($_POST, "SubmitResult");

# make sure the user can view the page
if (!CheckAuthorization(PRIV_SYSADMIN, PRIV_USERADMIN)) {  return;  }

# pull up record of user being edited
$UserToEdit = new CWUser(intval(GetArrayValue($_SESSION, "IdOfUserBeingEdited")));
unset($_SESSION["IdOfUserBeingEdited"]);

# if the user wasn't found
if ($UserToEdit->Status() !== U_OKAY)
{
    # go back to the user list
    $GLOBALS["AF"]->SetJumpToPage("UserList");
    return;
}

$UEUI = new UserEditingUI($UserToEdit);

# if submit button pushed
if ($SubmitResult == "Save Changes")
{
    # update the user information
    $UEUI->UpdateUserAttributes($_POST, FALSE, TRUE);
    $Errors = $UEUI->UpdateUserFields(CWUser::GetCustomUserFields());

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

    # update saved search mailing frequencies if mailings are enabled
    if ($GLOBALS["SysConfig"]->UserAgentsEnabled())
    {
        UpdateSavedSearches($UserToEdit);
    }

    # extract values from the form that need additional checks
    $F_NewPassword = GetArrayValue($_POST, "F_NewPassword");
    $F_Privileges = GetArrayValue($_POST, "F_Privileges", array());
    $F_UserDisabled = GetArrayValue($_POST, "F_UserDisabled", FALSE);
    $F_ActivateAccount = GetArrayValue($_POST, "F_ActivateAccount", FALSE);

    # change the user's password if necessary
    if (strlen($F_NewPassword))
    {
        $UserToEdit->SetPassword($F_NewPassword);
    }

    # don't allow non sysadmin to turn off sysadmin, user for a sysadmin
    if ($UserToEdit->HasPriv(PRIV_SYSADMIN)
        && $GLOBALS["User"]->HasPriv(PRIV_USERADMIN)
        && !$GLOBALS["User"]->HasPriv(PRIV_SYSADMIN))
    {
        $F_Privileges[] = PRIV_SYSADMIN;
        $F_Privileges[] = PRIV_USERADMIN;
    }

    # don't allow sysadmin turn off sysadmin, user for himself
    if ($UserToEdit->Get("UserId") == $GLOBALS["User"]->Get("UserId")
        && $GLOBALS["User"]->HasPriv(PRIV_SYSADMIN))
    {
        $F_Privileges[] = PRIV_SYSADMIN;
        $F_Privileges[] = PRIV_USERADMIN;
    }

    # update the user's privileges
    # (note: SetPrivList clears the list first, so it nukes PRIV_USERDISABLED)
    $UserToEdit->SetPrivList($F_Privileges);

    # disable the user account if necessary, but don't allow users to disable
    # their own accounts
    if ($F_UserDisabled && $UserToEdit->Get("UserId") != $GLOBALS["User"]->Get("UserId"))
    {
        $UserToEdit->GrantPriv(PRIV_USERDISABLED);
    }

    # activate the user account if necessary
    if ($F_ActivateAccount)
    {
        # enable account for login
        $UserToEdit->RevokePriv(PRIV_USERDISABLED);
        $UserToEdit->IsActivated(TRUE);

        # signal that user has been activated
        $GLOBALS["AF"]->SignalEvent(
            "EVENT_USER_VERIFIED", array("UserId" => $UserToEdit->Id()));
    }

    # go back to the user list
    $GLOBALS["AF"]->SetJumpToPage("UserList");

    # update search and recommender DBs
    $UserToEdit->GetResource()->QueueSearchAndRecommenderUpdate();
}

# delete the user
else if ($SubmitResult == "Delete")
{
    # but first go to the confirmation page
    $_SESSION["UserRemoveArray"] = array($UserToEdit->Id());
    $GLOBALS["AF"]->SetJumpToPage("ConfirmRemoveUser");
}

# delete a saved search
else if (!is_null($F_DeleteSavedSearch))
{
    # update the user information
    $UEUI->UpdateUserAttributes($_POST);
    $Errors = $UEUI->UpdateUserFields(CWUser::GetCustomUserFields());

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

    # update saved search mailing frequencies if mailings are enabled
    if ($GLOBALS["SysConfig"]->UserAgentsEnabled())
    {
        UpdateSavedSearches($UserToEdit);
    }

    # delete the saved search
    $Search = new SavedSearch($F_DeleteSavedSearch);
    $Search->Delete();

    # return to the user editing page
    $AF->SetJumpToPage("EditUser&ID=".urlencode($UserToEdit->Id()));
}

else
{
    # return to front page
    $AF->SetJumpToPage("UserList");
}
