You are here

purge_users.module in Auto Purge Users 8

Purge users module file.

File

purge_users.module
View source
<?php

/**
 * @file
 * Purge users module file.
 */
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\user\Entity\User;
use Drupal\Core\Url;
use Drupal\Core\Database\Query\Condition;
use Drupal\Core\Session\AccountInterface;

/**
 * Implements hook_cron().
 */
function purge_users_cron() {
  $config = \Drupal::config('purge_users.settings');
  if ($config
    ->get('purge_on_cron') == 1) {
    $result = purge_users_get_user_ids();

    // Add items to queue.
    $queue_factory = \Drupal::service('queue');
    $queue = $queue_factory
      ->get('purge_users');
    $users = User::loadMultiple($result);

    // Process the queue till it is empty.
    if ($queue
      ->numberOfItems() == 0) {
      foreach ($users as $user_id) {
        $queue
          ->createItem($user_id);
      }
    }
  }
}

/**
 * Get users who never login at all.
 */
function purge_users_never_loggedin_user_ids($param, $user_roles = array()) {

  // Get a time stamp according to the period selected.
  $logindate = '';
  if (!empty($param['never_login_value'])) {
    $logindate = strtotime('-' . $param['never_login_value'] . ' ' . $param['never_login_period']);
  }

  // Query through db table to get users ids.
  $db = \Drupal::database();
  $query = $db
    ->select('users_field_data', 'u')
    ->distinct();
  $query
    ->leftjoin('user__roles', 'ur', 'ur.entity_id = u.uid');
  $query
    ->fields('u', array(
    'uid',
  ));
  $query
    ->condition('u.uid', 1, '>');
  if (!empty($param['login_value'])) {
    $query
      ->condition('u.created', $logindate, '<');
    $query
      ->condition('u.login', 0);
  }
  if (in_array(AccountInterface::AUTHENTICATED_ROLE, $user_roles)) {
    $db_or = new Condition('OR');
    $db_or
      ->isNull('ur.roles_target_id');
    $db_or
      ->condition('ur.roles_target_id', $user_roles, 'IN');
    $query
      ->condition($db_or);
  }
  else {
    $query
      ->condition('ur.roles_target_id', $user_roles, 'IN');
  }
  $uids = $query
    ->execute()
    ->fetchCol();
  return $uids;
}

/**
 * Get users who didn't login at all.
 */
function purge_users_not_loggedin_user_ids($param, $user_roles = array()) {

  // Get a time stamp according to the period selected.
  $logindate = '';
  if (!empty($param['login_value'])) {
    $logindate = strtotime('-' . $param['login_value'] . ' ' . $param['login_period']);
  }

  // Query through db table to get users ids.
  $db = \Drupal::database();
  $query = $db
    ->select('users_field_data', 'u')
    ->distinct();
  $query
    ->leftjoin('user__roles', 'ur', 'ur.entity_id = u.uid');
  $query
    ->fields('u', array(
    'uid',
  ));
  $query
    ->condition('u.uid', 1, '>');
  if (!empty($param['login_value'])) {
    $query
      ->condition('u.login', $logindate, '<');
    $query
      ->condition('u.login', 0, '!=');
  }
  if (in_array(AccountInterface::AUTHENTICATED_ROLE, $user_roles)) {
    $db_or = new Condition('OR');
    $db_or
      ->isNull('ur.roles_target_id');
    $db_or
      ->condition('ur.roles_target_id', $user_roles, 'IN');
    $query
      ->condition($db_or);
  }
  else {
    $query
      ->condition('ur.roles_target_id', $user_roles, 'IN');
  }
  $uids = $query
    ->execute()
    ->fetchCol();
  return $uids;
}

/**
 * Get inactive user ids.
 */
function purge_users_inactive_user_ids($param, $user_roles = array()) {

  // Get a time stamp according to the period selected.
  $inactivedate = '';
  if (!empty($param['inactive_value'])) {
    $inactivedate = strtotime('-' . $param['inactive_value'] . ' ' . $param['inactive_period']);
  }

  // Query through db table to get users ids.
  $db = \Drupal::database();
  $query = $db
    ->select('users_field_data', 'u')
    ->distinct();
  $query
    ->leftjoin('user__roles', 'ur', 'ur.entity_id = u.uid');
  $query
    ->fields('u', array(
    'uid',
  ));
  $query
    ->condition('u.uid', 1, '>');
  if (!empty($param['inactive_value'])) {
    $query
      ->condition('u.created', $inactivedate, '<');
    $query
      ->condition('u.login', 0);
    $query
      ->condition('u.status', 0);
  }
  if (in_array(AccountInterface::AUTHENTICATED_ROLE, $user_roles)) {
    $db_or = new Condition('OR');
    $db_or
      ->isNull('ur.roles_target_id');
    $db_or
      ->condition('ur.roles_target_id', $user_roles, 'IN');
    $query
      ->condition($db_or);
  }
  else {
    $query
      ->condition('ur.roles_target_id', $user_roles, 'IN');
  }
  $uids = $query
    ->execute()
    ->fetchCol();
  return $uids;
}

/**
 * Get blocked user ids.
 */
function purge_users_blocked_user_ids($param, $user_roles = array()) {

  // Get a time stamp according to the period selected.
  $blockdate = '';
  if (!empty($param['blocked_value'])) {
    $blockdate = strtotime('-' . $param['blocked_value'] . ' ' . $param['blocked_period']);
  }

  // Query through db table to get users ids.
  $db = \Drupal::database();
  $query = $db
    ->select('users_field_data', 'u')
    ->distinct();
  $query
    ->leftjoin('user__roles', 'ur', 'ur.entity_id = u.uid');
  $query
    ->fields('u', array(
    'uid',
  ));
  $query
    ->condition('u.uid', 1, '>');
  if (!empty($param['blocked_period'])) {
    $query
      ->condition('u.created', $blockdate, '<');
    $query
      ->condition('u.login', $blockdate, '<');
    $query
      ->condition('u.login', 0, '!=');
    $query
      ->condition('u.status', 0);
  }
  if (in_array(AccountInterface::AUTHENTICATED_ROLE, $user_roles)) {
    $db_or = new Condition('OR');
    $db_or
      ->isNull('ur.roles_target_id');
    $db_or
      ->condition('ur.roles_target_id', $user_roles, 'IN');
    $query
      ->condition($db_or);
  }
  else {
    $query
      ->condition('ur.roles_target_id', $user_roles, 'IN');
  }
  $uids = $query
    ->execute()
    ->fetchCol();
  return $uids;
}

/**
 * The batch finish handler.
 */
function purge_users_batch_completed($success, $results, $operations) {
  if ($success) {
    $purged = isset($results['purged']) ? $results['purged'] : 0;
    $message = t('@count Users has been purged.', array(
      '@count' => $purged,
    ));
    drupal_set_message($message);
  }
  else {
    $error_operation = reset($operations);
    $message = t('An error occurred while processing %error_operation with arguments: @arguments', array(
      '%error_operation' => $error_operation[0],
      '@arguments' => print_r($error_operation[1], TRUE),
    ));
    drupal_set_message($message, 'error');
  }
  return new RedirectResponse(Url::fromRoute('purge_users.settings')
    ->toString());
}

/**
 * Get user ids to purge.
 */
function purge_users_get_user_ids() {

  // Get form submissions.
  $result = array();
  $config = \Drupal::config('purge_users.settings');
  $user_roles = array_filter($config
    ->get('purge_users_roles'));
  $enable_never_loggedin = $config
    ->get('enabled_never_loggedin_users');
  $enable_loggedin = $config
    ->get('enabled_loggedin_users');
  $enable_inactive = $config
    ->get('enabled_inactive_users');
  $enable_blocked = $config
    ->get('enabled_blocked_users');
  $param = array(
    'never_login_value' => $config
      ->get('user_never_lastlogin_value'),
    'never_login_period' => $config
      ->get('user_never_lastlogin_period'),
    'login_value' => $config
      ->get('user_lastlogin_value'),
    'login_period' => $config
      ->get('user_lastlogin_period'),
    'inactive_value' => $config
      ->get('user_inactive_value'),
    'inactive_period' => $config
      ->get('user_inactive_period'),
    'blocked_value' => $config
      ->get('user_blocked_value'),
    'blocked_period' => $config
      ->get('user_blocked_period'),
  );

  // Get user ids to purge.
  $never_loggedin_users = array();
  $not_loggedin_users = array();
  $inactive_users = array();
  $blocked_users = array();

  // Get users who have never logged in at all.
  if ($enable_never_loggedin == 1) {
    $never_loggedin_users = purge_users_never_loggedin_user_ids($param, $user_roles);
  }

  // Get users who have not logged in at all.
  if ($enable_loggedin == 1) {
    $not_loggedin_users = purge_users_not_loggedin_user_ids($param, $user_roles);
  }

  // Get users who didn't activate their account.
  if ($enable_inactive == 1) {
    $inactive_users = purge_users_inactive_user_ids($param, $user_roles);
  }

  // Get the users who are blocked.
  if ($enable_blocked == 1) {
    $blocked_users = purge_users_blocked_user_ids($param, $user_roles);
  }

  // Merge results to create an array of user ids to purge.
  $result = array_merge($never_loggedin_users, $not_loggedin_users, $inactive_users, $blocked_users);
  return $result;
}

/**
 * Send notification email.
 */
function purge_users_send_notification_email($account) {

  // Email to be sent to this Email ID.
  $mailManager = \Drupal::service('plugin.manager.mail');
  $module = 'purge_users';
  $key = 'delete_users';
  $to = $account
    ->get('mail')->value;
  $config = \Drupal::config('purge_users.settings');
  $message = $config
    ->get('inactive_user_notify_text');
  $moduleHandler = \Drupal::service('module_handler');
  if ($moduleHandler
    ->moduleExists('token')) {
    $token_service = \Drupal::token();
    $message = $token_service
      ->replace($message, array(
      'user' => $account,
    ));
  }
  $params = [
    'subject' => t('Your account is deleted.'),
    'body' => $message,
  ];
  $langcode = $account
    ->getPreferredLangcode();
  $send = TRUE;
  $mailManager
    ->mail($module, $key, $to, $langcode, $params, NULL, $send);
}

/**
 * Implements hook_mail().
 */
function purge_users_mail($key, &$message, $params) {
  switch ($key) {
    case 'delete_users':
      $message['subject'] = $params['subject'];
      $message['body'][] = $params['body'];
      break;
  }
}

Functions

Namesort descending Description
purge_users_batch_completed The batch finish handler.
purge_users_blocked_user_ids Get blocked user ids.
purge_users_cron Implements hook_cron().
purge_users_get_user_ids Get user ids to purge.
purge_users_inactive_user_ids Get inactive user ids.
purge_users_mail Implements hook_mail().
purge_users_never_loggedin_user_ids Get users who never login at all.
purge_users_not_loggedin_user_ids Get users who didn't login at all.
purge_users_send_notification_email Send notification email.