You are here

function ldap_user_update_8301 in Lightweight Directory Access Protocol (LDAP) 8.3

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

Convert ldap_user_identities table to authmap.

File

ldap_user/ldap_user.install, line 29
Install, update and uninstall functions for the LDAP User module.

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' => \Drupal::l('External Auth', $external_link),
    ]);
    drupal_set_message($message, "error");
    throw new UpdateException($message);
  }
  if (empty($sandbox)) {
    $sandbox['progress'] = 0;
    $sandbox['current_id'] = 0;
    $sandbox['max'] = db_query('SELECT COUNT(DISTINCT aid) FROM {ldap_user_identities}')
      ->fetchField();
  }
  $limit = 25;
  $result = db_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 = user_load($identity->uid);
    $authmap = \Drupal::service('externalauth.authmap');
    $authmap
      ->save($account, 'ldap_user', $identity->identifier);

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