1.20.x user.entity.inc protected UserStorageController::postSave(EntityInterface $entity, $update)

Overrides EntityDatabaseStorageController::postSave().

Parameters

User $entity: The user entity that has just been saved.

Overrides EntityDatabaseStorageController::postSave

File

modules/user/user.entity.inc, line 437
Entity classes and controllers for User module.

Class

UserStorageController
Controller class for users.

Code

protected function postSave(EntityInterface $entity, $update) {

  if ($update) {
    // If the password has been changed, delete all open sessions for the
    // user and recreate the current one.
    if ($entity->pass != $entity->original->pass) {
      backdrop_session_destroy_uid($entity->uid);
      if ($entity->uid == $GLOBALS['user']->uid) {
        backdrop_session_regenerate();
      }
    }

    // Remove roles that are no longer enabled for the user.
    $entity->roles = array_values(array_filter($entity->roles));

    // Reload user roles if provided.
    if ($entity->roles != $entity->original->roles) {
      db_delete('users_roles')
        ->condition('uid', $entity->uid)
        ->execute();

      $query = db_insert('users_roles')->fields(array('uid', 'role'));
      foreach ($entity->roles as $role_name) {
        if (!in_array($role_name, array(BACKDROP_ANONYMOUS_ROLE, BACKDROP_AUTHENTICATED_ROLE))) {
          $query->values(array(
            'uid' => $entity->uid,
            'role' => $role_name,
          ));
        }
      }
      $query->execute();
    }

    // If the user was blocked, delete the user's sessions to force a logout.
    if ($entity->original->status != $entity->status && $entity->status == 0) {
      backdrop_session_destroy_uid($entity->uid);
    }

    // Send emails after we have the new user object.
    if ($entity->status != $entity->original->status) {
      // The user's status is changing; conditionally send notification email.
      $op = $entity->status == 1 ? 'status_activated' : 'status_blocked';
      _user_mail_notify($op, $entity);
    }
  }
  else {
    // Save user roles. Skip built-in roles, and ones that were already saved
    // to the database during hook calls.
    $role_names_to_skip = array_merge(array(BACKDROP_ANONYMOUS_ROLE, BACKDROP_AUTHENTICATED_ROLE), db_query('SELECT role FROM {users_roles} WHERE uid = :uid', array(':uid' => $entity->uid))->fetchCol());
    if ($roles_to_save = array_diff($entity->roles, $role_names_to_skip)) {
      $query = db_insert('users_roles')->fields(array('uid', 'role'));
      foreach ($roles_to_save as $role_name) {
        $query->values(array(
          'uid' => $entity->uid,
          'role' => $role_name,
        ));
      }
      $query->execute();
    }
  }
}