You are here

purge_users.module in Auto Purge Users 8.2

Purge users module file.

File

purge_users.module
View source
<?php

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

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

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

    // Process the queue till it is empty.
    if ($queue
      ->numberOfItems() == 0) {
      foreach ($user_ids as $user_id) {
        $queue
          ->createItem($user_id);
      }
    }
  }
  if ($config
    ->get('send_email_user_before_notification') == 1) {
    $op = 'notification_users';
    $user_ids = array_unique(purge_users_get_user_ids($op));
    if (!empty($user_ids)) {
      foreach ($user_ids as $user_id) {
        $account = User::load($user_id);
        purge_users_send_notification_email($account, 'notification_users');
      }
    }
  }
}

/**
 * Get users who never login at all.
 */
function purge_users_never_loggedin_user_ids($param, $included_user_roles = [], $excluded_user_roles = []) {

  // 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();
  $exist_query = $db
    ->select('user__roles', 'ur');
  $exist_query
    ->fields('ur', [
    'entity_id',
  ]);
  $exist_query
    ->where('ur.entity_id = u.uid');
  $exist_query
    ->condition('ur.roles_target_id', $included_user_roles, 'IN');
  $not_exist_query = $db
    ->select('user__roles', 'ur');
  $not_exist_query
    ->fields('ur', [
    'entity_id',
  ]);
  $not_exist_query
    ->where('ur.entity_id = u.uid');
  $not_exist_query
    ->condition('ur.roles_target_id', $excluded_user_roles, 'IN');
  $query = $db
    ->select('users_field_data', 'u')
    ->distinct();
  $query
    ->leftjoin('user__roles', 'ur', 'ur.entity_id = u.uid');
  $query
    ->fields('u', [
    'uid',
  ]);
  $query
    ->condition('u.uid', 1, '>');
  if (!empty($param['never_login_value'])) {
    $query
      ->condition('u.created', $logindate, '<');
    $query
      ->condition('u.login', 0);
  }
  if (in_array(AccountInterface::AUTHENTICATED_ROLE, $included_user_roles)) {
    $db_or = new Condition('OR');
    $db_or
      ->isNull('ur.roles_target_id');
    $db_or
      ->exists($exist_query);
    $query
      ->condition($db_or);
  }
  else {
    $query
      ->exists($exist_query);
  }
  if ($param['disregard_blocked_users']) {
    $query
      ->condition('u.status', 1);
  }
  $query
    ->notExists($not_exist_query);
  $uids = $query
    ->execute()
    ->fetchCol();

  // Allow other modules to modify the result.
  \Drupal::moduleHandler()
    ->alter('purge_never_loggedin_user_ids', $uids);
  return $uids;
}

/**
 * Get users who didn't login at all.
 */
function purge_users_not_loggedin_user_ids($param, $included_user_roles = [], $excluded_user_roles = []) {

  // 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();
  $exist_query = $db
    ->select('user__roles', 'ur');
  $exist_query
    ->fields('ur', [
    'entity_id',
  ]);
  $exist_query
    ->where('ur.entity_id = u.uid');
  $exist_query
    ->condition('ur.roles_target_id', $included_user_roles, 'IN');
  $not_exist_query = $db
    ->select('user__roles', 'ur');
  $not_exist_query
    ->fields('ur', [
    'entity_id',
  ]);
  $not_exist_query
    ->where('ur.entity_id = u.uid');
  $not_exist_query
    ->condition('ur.roles_target_id', $excluded_user_roles, 'IN');
  $query = $db
    ->select('users_field_data', 'u')
    ->distinct();
  $query
    ->leftjoin('user__roles', 'ur', 'ur.entity_id = u.uid');
  $query
    ->fields('u', [
    '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, $included_user_roles)) {
    $db_or = new Condition('OR');
    $db_or
      ->isNull('ur.roles_target_id');
    $db_or
      ->exists($exist_query);
    $query
      ->condition($db_or);
  }
  else {
    $query
      ->exists($exist_query);
  }
  if ($param['disregard_blocked_users']) {
    $query
      ->condition('u.status', 1);
  }
  $query
    ->notExists($not_exist_query);
  $uids = $query
    ->execute()
    ->fetchCol();

  // Allow other modules to modify the result.
  \Drupal::moduleHandler()
    ->alter('purge_not_loggedin_user_ids', $uids);
  return $uids;
}

/**
 * Get inactive user ids.
 */
function purge_users_inactive_user_ids($param, $included_user_roles = [], $excluded_user_roles = []) {

  // 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();
  $exist_query = $db
    ->select('user__roles', 'ur');
  $exist_query
    ->fields('ur', [
    'entity_id',
  ]);
  $exist_query
    ->where('ur.entity_id = u.uid');
  $exist_query
    ->condition('ur.roles_target_id', $included_user_roles, 'IN');
  $not_exist_query = $db
    ->select('user__roles', 'ur');
  $not_exist_query
    ->fields('ur', [
    'entity_id',
  ]);
  $not_exist_query
    ->where('ur.entity_id = u.uid');
  $not_exist_query
    ->condition('ur.roles_target_id', $excluded_user_roles, 'IN');
  $query = $db
    ->select('users_field_data', 'u')
    ->distinct();
  $query
    ->leftjoin('user__roles', 'ur', 'ur.entity_id = u.uid');
  $query
    ->fields('u', [
    '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, $included_user_roles)) {
    $db_or = new Condition('OR');
    $db_or
      ->isNull('ur.roles_target_id');
    $db_or
      ->exists($exist_query);
    $query
      ->condition($db_or);
  }
  else {
    $query
      ->exists($exist_query);
  }
  $query
    ->notExists($not_exist_query);
  $uids = $query
    ->execute()
    ->fetchCol();

  // Allow other modules to modify the result.
  \Drupal::moduleHandler()
    ->alter('purge_inactive_user_ids', $uids);
  return $uids;
}

/**
 * Get blocked user ids.
 */
function purge_users_blocked_user_ids($param, $included_user_roles = [], $excluded_user_roles = []) {

  // 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();
  $exist_query = $db
    ->select('user__roles', 'ur');
  $exist_query
    ->fields('ur', [
    'entity_id',
  ]);
  $exist_query
    ->where('ur.entity_id = u.uid');
  $exist_query
    ->condition('ur.roles_target_id', $included_user_roles, 'IN');
  $not_exist_query = $db
    ->select('user__roles', 'ur');
  $not_exist_query
    ->fields('ur', [
    'entity_id',
  ]);
  $not_exist_query
    ->where('ur.entity_id = u.uid');
  $not_exist_query
    ->condition('ur.roles_target_id', $excluded_user_roles, 'IN');
  $query = $db
    ->select('users_field_data', 'u')
    ->distinct();
  $query
    ->leftjoin('user__roles', 'ur', 'ur.entity_id = u.uid');
  $query
    ->fields('u', [
    '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, $included_user_roles)) {
    $db_or = new Condition('OR');
    $db_or
      ->isNull('ur.roles_target_id');
    $db_or
      ->exists($exist_query);
    $query
      ->condition($db_or);
  }
  else {
    $query
      ->exists($exist_query);
  }
  $query
    ->notExists($not_exist_query);
  $uids = $query
    ->execute()
    ->fetchCol();

  // Allow other modules to modify the result.
  \Drupal::moduleHandler()
    ->alter('purge_blocked_user_ids', $uids);
  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.', [
      '@count' => $purged,
    ]);
    \Drupal::messenger()
      ->addMessage($message);
  }
  else {
    $error_operation = reset($operations);
    $message = t('An error occurred while processing %error_operation with arguments: @arguments', [
      '%error_operation' => $error_operation[0],
      '@arguments' => print_r($error_operation[1], TRUE),
    ]);
    \Drupal::messenger()
      ->addError($message);
  }
  return new RedirectResponse(Url::fromRoute('purge_users.settings')
    ->toString());
}

/**
 * Get user ids to purge.
 */
function purge_users_get_user_ids($op = 'purge_users') {

  // Get form submissions.
  $result = [];
  $config = \Drupal::config('purge_users.settings');
  $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');
  $send_email_user_before_notification = $config
    ->get('send_email_user_before_notification');
  $param = [
    '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'),
    'disregard_blocked_users' => $config
      ->get('disregard_blocked_users'),
  ];
  if ($op == 'notification_users' && $send_email_user_before_notification == 1) {
    $user_before_notification_value = $config
      ->get('user_before_notification_value');
    $param['never_login_value'] = $param['login_value'] = $param['inactive_value'] = $param['blocked_value'] = $user_before_notification_value;
  }
  $included_user_roles = array_filter($config
    ->get('purge_included_users_roles'));
  $excluded_user_roles = array_filter($config
    ->get('purge_excluded_users_roles'));

  // Get user ids to purge.
  $never_loggedin_users = [];
  $not_loggedin_users = [];
  $inactive_users = [];
  $blocked_users = [];

  // Get users who have never logged in at all.
  if ($enable_never_loggedin == 1) {
    $never_loggedin_users = purge_users_never_loggedin_user_ids($param, $included_user_roles, $excluded_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, $included_user_roles, $excluded_user_roles);
  }

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

  // Get the users who are blocked.
  if ($enable_blocked == 1) {
    $blocked_users = purge_users_blocked_user_ids($param, $included_user_roles, $excluded_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, $op = 'user_deletion') {

  // 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');
  $subject = $config
    ->get('inactive_user_notify_subject');
  if ($op == 'notification_users') {
    $subject = $config
      ->get('user_before_deletion_subject');
    $message = $config
      ->get('user_before_deletion_text');
    $params['subject'] = t('Your account will be deleted.');
  }
  $moduleHandler = \Drupal::service('module_handler');
  if ($moduleHandler
    ->moduleExists('token')) {
    $token_service = \Drupal::token();
    $message = $token_service
      ->replace($message, [
      'user' => $account,
    ]);
  }
  $params = [
    'subject' => $subject,
    '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.