function simple_ldap_user_cron in Simple LDAP 8
Implements hook_cron().
File
- modules/
simple_ldap_user/ simple_ldap_user.module, line 142
Code
function simple_ldap_user_cron() {
// See if there are any restrictions on how frequently to check the LDAP
// server. If so, and not enough time has elapsed, return without doing
// anything.
$config = \Drupal::config('simple_ldap.user');
$step_in_seconds = !empty($config
->get('cron_frequency')) ? $config
->get('cron_frequency') : 0;
if (!empty($step_in_seconds)) {
$curr_time = \Drupal::time()
->getRequestTime();
// $time only increments in steps of $step_in_seconds.
$time = (int) floor($curr_time / $step_in_seconds) * $step_in_seconds;
$state_key = 'simple_ldap_user.blocked_users.last_check';
$expires = \Drupal::state()
->get($state_key, 0);
if ($time <= $expires) {
\Drupal::logger('simple_ldap')
->notice('Simple LDAP user cron update skipped until @expires.', [
'@expires' => date('r', $expires),
]);
return;
}
// If we proceed, set the next marker.
\Drupal::state()
->set($state_key, $time);
}
/**
* @var \Drupal\simple_ldap_user\SimpleLdapUserAuthenticator $authenticator
*/
$authenticator = \Drupal::service('simple_ldap_user.auth');
// Load all the users except anonymous and user #1.
$users = User::loadMultiple();
$users = array_filter($users, function (UserInterface $user) use ($authenticator) {
return $authenticator
->canAuthenticate($user
->getAccountName());
});
/**
* @var \Drupal\simple_ldap_user\SimpleLdapUserManager $manager
* @var \Drupal\simple_ldap_user\SimpleLdapUserSync $syncer
*/
$manager = \Drupal::service('simple_ldap_user.manager');
$syncer = \Drupal::service('simple_ldap_user.sync');
array_map(function (UserInterface $user) use ($manager, $syncer) {
// Block the user if they are not found in the LDAP server.
// TODO: Load all the LDAP users in a single request for better performance.
$ldap_user = $manager
->getLdapUser($user
->getAccountName());
$was_blocked = $user
->isBlocked();
$force_save = FALSE;
if ($ldap_user === FALSE) {
if (!$was_blocked) {
// There is an active drupal user, but no LDAP user associated. Block
// the drupal user. The user base is **completely** managed by LDAP.
\Drupal::logger('simple_ldap')
->notice('Simple LDAP user cron blocking @name.', [
'@name' => $user
->getAccountName(),
]);
$user
->block();
$user
->save();
}
// There is no LDAP data to synchronize.
return;
}
if ($ldap_user && $was_blocked) {
// The presence of an LDAP user is reason enough to unblock the Drupal
// user.
\Drupal::logger('simple_ldap')
->notice('Simple LDAP user cron activating @name.', [
'@name' => $user
->getAccountName(),
]);
$user
->activate();
$force_save = TRUE;
}
$syncer
->updateDrupalUser($ldap_user, $user, $force_save);
}, $users);
}