You are here

function user_expire_expire_by_role_warning in User Expire 8

Same name and namespace in other branches
  1. 7 user_expire.module \user_expire_expire_by_role_warning()

Warns users with an upcoming expiration by roles.

1 call to user_expire_expire_by_role_warning()
user_expire_cron in ./user_expire.module
Implements hook_cron().

File

./user_expire.module, line 313
Main module file for User expire module.

Code

function user_expire_expire_by_role_warning() {
  $config = \Drupal::configFactory()
    ->getEditable('user_expire.settings');
  $logger = \Drupal::logger('user_expire');
  $last_run = \Drupal::state()
    ->get('user_expire_last_run', 0);
  $warning_frequency = $config
    ->get('frequency');

  // Warn people every 2 days.
  if ($last_run && $last_run > \Drupal::time()
    ->getRequestTime() - $warning_frequency) {
    \Drupal::logger('user_expire')
      ->debug('Skipping warning as it was run within the last @hours hours', [
      '@hours' => $warning_frequency / (60 * 60),
    ]);
    return;
  }

  // Find people to warn.
  $rules = user_expire_get_role_rules();
  $warning_offset = $config
    ->get('offset');
  foreach ($rules as $rid => $inactivity_period) {
    $uids_to_warn = user_expire_find_users_to_expire_by_role($rid, $inactivity_period - $warning_offset);
    if ($uids_to_warn) {
      foreach ($uids_to_warn as $uid) {
        $account = \Drupal::entityTypeManager()
          ->getStorage('user')
          ->load($uid->uid);
        if ($account) {
          $logger
            ->debug('Skipping warning @uid as it failed to load a valid user', [
            '@uid' => $uid->uid,
          ]);
        }
        else {
          $logger
            ->info('Warning about expiring account @name by role', [
            '@name' => $account
              ->getAccountName(),
          ]);
          \Drupal::service('plugin.manager.mail')
            ->mail('user_expire', 'expiration_warning', $account
            ->getEmail(), $account
            ->getPreferredLangcode(), [
            'account' => $account,
          ]);
        }
      }
    }
  }
  \Drupal::state()
    ->set('user_expire_last_run', \Drupal::time()
    ->getRequestTime());
}