You are here

function force_password_change_edit_role in Force Password Change 2.0.x

Same name and namespace in other branches
  1. 8 force_password_change.module \force_password_change_edit_role()
  2. 7.2 force_password_change.module \force_password_change_edit_role()
  3. 7 force_password_change.module \force_password_change_edit_role()

Callback #submit function called on the role edit page when the user clicks the save button.

1 string reference to 'force_password_change_edit_role'
force_password_change_form_alter in ./force_password_change.module
Implements hook_form_alter().

File

./force_password_change.module, line 321

Code

function force_password_change_edit_role(array $form, FormStateInterface $form_state) {
  $db = \Drupal::database();

  // Add role to the {force_password_change_roles} form if it doesn't exist.
  $exists = $db
    ->query('SELECT 1 FROM {force_password_change_roles} WHERE rid = :rid', [
    ':rid' => $form_state
      ->getValue('id'),
  ])
    ->fetchField();
  if (!$exists) {
    $db
      ->insert('force_password_change_roles')
      ->fields([
      'rid' => $form_state
        ->getValue('id'),
      'last_force' => 0,
    ])
      ->execute();
  }

  // Only flag user's accounts to be changed if the checkbox
  // was selected.
  if ($form_state
    ->getValue('force_password_change')) {

    // Get the UIDs for all users in the role.
    if ($form_state
      ->getValue('id') == 'authenticated') {
      $sql = 'SELECT uid FROM {users} WHERE uid > 0';
      $values = [];
    }
    else {
      $sql = 'SELECT entity_id FROM {user__roles} WHERE roles_target_id = :rid ';
      $values[':rid'] = $form_state
        ->getValue('id');
    }
    $uids = $db
      ->query($sql, $values)
      ->fetchCol();
    if (count($uids)) {

      // Flag the users accounts.
      \Drupal::service('force_password_change.service')
        ->forceUsersPasswordChange($uids);
    }

    // Set the last force time for the role for statistics sake.
    $request_time = \Drupal::time()
      ->getRequestTime();
    $query = $db
      ->update('force_password_change_roles')
      ->fields([
      'last_force' => $request_time,
    ])
      ->condition('rid', $form_state
      ->getValue('id'))
      ->execute();
    if (\Drupal::config('force_password_change.settings')
      ->get('check_login_only')) {
      $description = t('User with the %role_name role will be required to change their password upon their next login.', [
        '%role_name' => $form_state
          ->getValue('label'),
      ]);
    }
    else {
      $description = t('Users in the %role_name role will be required to immediately change their password', [
        '%role_name' => $form_state
          ->getValue('label'),
      ]);
    }
    \Drupal::messenger()
      ->addMessage($description);
  }
}