You are here

function roleassign_user_presave in RoleAssign 8

Same name and namespace in other branches
  1. 7.2 roleassign.module \roleassign_user_presave()
  2. 7 roleassign.module \roleassign_user_presave()

Implements hook_ENTITY_TYPE_presave() as hook_user_presave().

File

./roleassign.module, line 154
Allows site administrators to delegate the task of managing user's roles.

Code

function roleassign_user_presave($account) {
  if (roleassign_restrict_access()) {
    $assignable_roles = array_filter(\Drupal::config('roleassign.settings')
      ->get('roleassign_roles'));
    $new_roles = $account
      ->getRoles();

    // Check the newly assigned roles, and whether the restricted
    // user has privileges to do so, based on the RoleAssign settings.
    foreach ($new_roles as $new_role) {
      if (!in_array($new_role, $assignable_roles)) {

        // Current user does not have privileges to change this role.
        if (($key = array_search($new_role, $new_roles)) !== FALSE) {
          unset($new_roles[$key]);
        }
      }
    }
    if (!$account
      ->isNew()) {
      $original_account = $account->original;
      $original_roles = $original_account
        ->getRoles();

      // Get a list of unassignable roles and add them to the new account roles
      // if they were assigned originally to the account.
      $unassignable_roles = roleassign_get_unassignable_roles();
      foreach ($unassignable_roles as $unassignable_role) {
        if (in_array($unassignable_role, $original_roles)) {

          // This account will need to get this role again, since the current
          // user is not allowed to mess with it.
          $new_roles[] = $unassignable_role;
        }
      }
    }

    // $newroles now contains a list of roles (un)assigned by the
    // restricted user + unassigneable roles that should stay unchanged.
    $account->roles = $new_roles;
  }
}