You are here

function ldap_user_update_8301 in Lightweight Directory Access Protocol (LDAP) 8.4

Same name and namespace in other branches
  1. 8.3 ldap_user/ldap_user.install \ldap_user_update_8301()

Convert ldap_user_identities table to authmap.

File

ldap_user/ldap_user.install, line 33

Code

function ldap_user_update_8301(&$sandbox) {

  // Check for externalauth module (which has been a dependency for ages).
  if (!\Drupal::moduleHandler()
    ->moduleExists('externalauth')) {
    $external_link = Url::fromUri('https://drupal.org/project/externalauth');
    $message = t('Please install the 8301 %external_link module.', [
      '%external_link' => Link::fromTextAndUrl('External Auth', $external_link),
    ]);
    \Drupal::messenger()
      ->addError($message);
    throw new UpdateException($message);
  }
  $connection = Database::getConnection();
  if (empty($sandbox)) {
    $sandbox['progress'] = 0;
    $sandbox['current_id'] = 0;
    $sandbox['max'] = $connection
      ->query('SELECT COUNT(DISTINCT aid) FROM {ldap_user_identities}')
      ->fetchField();
  }
  $limit = 25;
  $result = $connection
    ->select('ldap_user_identities')
    ->fields('ldap_user_identities', [
    'aid',
    'uid',
    'identifier',
  ])
    ->condition('aid', $sandbox['current_id'], '>')
    ->orderBy('aid')
    ->range(0, $limit)
    ->execute();

  // Iterate over the old table and create entries in the new table.
  foreach ($result as $identity) {

    // Load the user as the service expects an account.
    $account = \Drupal::entityTypeManager()
      ->getStorage('user')
      ->load($identity->uid);
    $authmap = \Drupal::service('externalauth.authmap');
    $authmap
      ->save($account, 'ldap_user', $identity->identifier);

    // Delete the row if successful.
    $connection
      ->query('DELETE FROM {ldap_user_identities} WHERE aid = :aid', [
      ':aid' => $identity->aid,
    ]);
    $sandbox['results'][] = $identity->aid . ' : ' . Html::escape($identity->identifier);
    $sandbox['progress']++;
    $sandbox['current_id'] = $identity->aid;
    $sandbox['message'] = Html::escape($identity->identifier);
  }
  if ($sandbox['progress'] != $sandbox['max']) {
    $sandbox['#finished'] = $sandbox['progress'] / $sandbox['max'];
  }
}