<?php

/**
 * @file
 * Install, update and uninstall functions for the LDAP API module.
 */

/**
 * Implements hook_install().
 */
function ldap_servers_install() {

}

/**
 * Implements hook_uninstall().
 */
function ldap_servers_uninstall() {
  variable_del('ldap_servers_encryption');
  variable_del('ldap_servers_require_ssl_for_credentials');
  variable_del('ldap_servers_encrypt_key');

}

/**
 * Implements hook_requirements().
 */
function ldap_servers_requirements($phase) {
  $requirements = [];
  $t = get_t();

  if ($phase == 'install') {
    $requirements['ldap_extension_loaded']['title'] = t('LDAP Extension Loaded');
    if (extension_loaded('ldap')) {
      $requirements['ldap_extension_loaded']['severity'] = REQUIREMENT_OK;
    }
    else {
      $requirements['ldap_extension_loaded']['severity'] = REQUIREMENT_ERROR;
      $requirements['ldap_extension_loaded']['description'] = t('No LDAP PHP Extension is loaded for PHP, so LDAP will not work properly.');
    }
  }

  if ($phase == 'runtime' && !extension_loaded('ldap')) {
    $requirements['ldap_extension_loaded']['title'] = t('LDAP Extension Loaded');
    $requirements['ldap_extension_loaded']['severity'] = REQUIREMENT_ERROR;
    $requirements['ldap_extension_loaded']['description'] = t('No LDAP PHP Extension is loaded for PHP, so LDAP will not work properly.');
  }

  if ($phase != "install" && db_table_exists('ldapauth')) {
    $requirements['ldap_servers']['title'] = t('LDAP Integration LDAP Auth to LDAP Servers Upgrade Concern');
    $requirements['ldap_servers']['severity'] = REQUIREMENT_WARNING;
    $requirements['ldap_servers']['value'] = NULL;
    $requirements['ldap_servers']['description'] = t('Upgrade from Drupal 6 LDAP Auth to Drupal 7
      LDAP Servers is not automatic.  LDAP Servers will need to be configured by hand.
      See http://drupal.org/node/1023016. This message will go away when the ldapauth database table is removed.');
  }
  // Check that ldapauth not installed.
  // Check enabled LDAP servers are configured and Drupal can connect to them.
  if ($phase == 'runtime') {
    $requirements['ldap_servers_enabled'] = [
      'title' => $t('LDAP Server status'),
      'value' => $t('Disabled'),
      'severity' => REQUIREMENT_WARNING,
    ];

    $servers = ldap_servers_get_servers(NULL, 'enabled');
    if (!empty($servers)) {
      unset($requirements['ldap_servers_enabled']);

      foreach ($servers as $server) {
        $server_req_key = 'ldap_servers_sid_' . $server->sid;
        $server_tokens = [
          '@host' => $server->address,
          '@sid' => $server->sid,
        ];
        $requirements[$server_req_key] = [
          'title' => $t('LDAP Server status: @sid (@host)', $server_tokens),
          'value' => $t('Connection: Failed, check logs for details.', $server_tokens),
          'severity' => REQUIREMENT_ERROR,
        ];

        try {
          $connect_result = $server->connect();
          if ($connect_result == LDAP_SUCCESS) {
            if ($server->bind_method == LDAP_SERVERS_BIND_METHOD_USER) {
              // Check bind anonymously if set to bind via user credentials.
              // The user has already logged in and so their is no dn or password
              // to check since LDAP doesn't store passwords.
              $bind_result = $server->bind(NULL, NULL, TRUE);
            }
            else {
              $bind_result = $server->bind();
            }
            if ($bind_result == LDAP_SUCCESS) {
              $requirements[$server_req_key]['value'] = $t('Connection: Success, Bind: Success', $server_tokens);
              $requirements[$server_req_key]['severity'] = REQUIREMENT_OK;
            }
          }
          $server->disconnect();
        }
        catch (Exception $e) {
        }
      }
    }
  }

  return $requirements;
}

/**
 * Implements hook_schema().
 */
function ldap_servers_schema() {
  module_load_include('inc', 'ldap_servers', 'ldap_servers.functions');
  // To get the LDAP_SERVERS_ENC_TYPE_CLEARTEXT constants issue#1209576.
  module_load_include('module', 'ldap_servers', 'ldap_servers');
  module_load_include('php', 'ldap_servers', 'LdapServerAdmin.class');

  $schema['ldap_servers'] = [
    'export' => [
      'key' => 'sid',
      'key name' => 'Server ID',
      'primary key' => 'numeric_sid',
      'identifier' => 'ldap_servers_conf',
      'api' => [
        'owner' => 'ldap_servers',
        'api' => 'ldap_servers',
        'minimum_version' => 1,
        'current_version' => 1,
      ],
    ],
    'primary key' => ['numeric_sid'],
    'unique keys' => ['name' => ['name']],
  ];

  $fields = LdapServerAdmin::fields();
  foreach ($fields as $name => $props) {
    if (isset($props['schema'])) {
      $schema['ldap_servers']['fields'][$name] = $props['schema'];
    }
  }

  return $schema;

}

/**
 * Rename ldap_servers type field to ldap_type.
 */
function ldap_servers_update_7100() {
  if (!ldap_servers_db_field_exists('ldap_servers', 'ldap_type') && ldap_servers_db_field_exists('ldap_servers', 'type')) {
    db_change_field('ldap_servers', 'type', 'ldap_type', [
      'type' => 'varchar',
      'length' => 20,
      'not null' => FALSE,
    ]);
  }

  return t('ldap_servers table field "type" renamed to "ldap_type"');

}

/**
 * Ldap_server table field changes.
 */
function ldap_servers_update_7101() {

  db_add_field(
    'ldap_servers',
    'allow_conflicting_drupal_accts',
    [
      'type' => 'int',
      'size' => 'tiny',
      'not null' => FALSE,
      'default' => 0,
    ]
  );

  db_add_field(
    'ldap_servers',
    'unique_persistent_attr',
    [
      'type' => 'varchar',
      'length' => '64',
      'not null' => FALSE,
    ]
  );

  db_add_field(
    'ldap_servers',
    'mail_template',
    [
      'type' => 'varchar',
      'length' => '255',
      'not null' => FALSE,
    ]
  );

  db_change_field('ldap_servers', 'ldap_to_drupal_user', 'ldap_to_drupal_user', [
    'type' => 'varchar',
    'length' => 1024,
    'not null' => FALSE,
  ]);

  db_change_field('ldap_servers', 'binddn', 'binddn', [
    'type' => 'varchar',
    'length' => 511,
  ]);

  return t('Updated LDAP Server to include "allow_conflicting_drupal_accts" and "unique_persistent_attr" fields.');
}

/**
 * Add bind_method field to ldap_servers table.
 */
function ldap_servers_update_7102() {

  if (!ldap_servers_db_field_exists('ldap_servers', 'bind_method')) {
    db_add_field('ldap_servers', 'bind_method', [
      'type' => 'int',
      'size' => 'tiny',
      'not null' => TRUE,
      'default' => 0,
    ]);
    $msg = t('"bind_method" field added to ldap_servers table');
  }

  return ($msg) ? $msg : t('No database changes made.');
}

/**
 * Add group_object_category field to ldap_servers table.
 */
function ldap_servers_update_7103() {

  if (!ldap_servers_db_field_exists('ldap_servers', 'group_object_category')) {
    db_add_field('ldap_servers', 'group_object_category', [
      'type' => 'varchar',
      'length' => 64,
      'not null' => FALSE,
    ]);
    $msg = t('"group_object_category" field added to ldap_servers table');
  }

  return ($msg) ? $msg : t('No database changes made.');
}

/**
 * Add pagination fields to ldap_servers table.
 */
function ldap_servers_update_7104() {

  if (!ldap_servers_db_field_exists('ldap_servers', 'search_pagination')) {
    db_add_field('ldap_servers', 'search_pagination', [
      'type' => 'int',
      'size' => 'tiny',
      'not null' => FALSE,
      'default' => 0,
    ]);
    $msg = t('"search_pagination" field added to ldap_servers table');
  }

  if (!ldap_servers_db_field_exists('ldap_servers', 'search_page_size')) {
    db_add_field('ldap_servers', 'search_page_size', [
      'type' => 'int',
      'size' => 'medium',
      'not null' => FALSE,
      'default' => 1000,
    ]);
    $msg .= '<br/>' . t('"search_page_size" field added to ldap_servers table');
  }

  if (!ldap_servers_db_field_exists('ldap_servers', 'unique_persistent_attr_binary')) {
    db_add_field('ldap_servers', 'unique_persistent_attr_binary', [
      'type' => 'int',
      'size' => 'tiny',
      'not null' => FALSE,
      'default' => 0,
    ]);
    $msg = t('"unique_persistent_attr_binary" field added to ldap_servers table');
  }

  return ($msg) ? $msg : t('No database changes made.');
}

/**
 * Enable ldap_user module.
 */
function ldap_servers_update_7105() {

  if (!module_exists('ldap_user')) {
    module_enable(['ldap_user']);
    $msg = t('LDAP User module enabled.  Some authentication and authorization functionality shifted to LDAP User module.');
  }

  return ($msg) ? $msg : t('LDAP User module was already enabled.  No action taken.');
}

/**
 * Add account_name_attr field to ldap_servers table.
 */
function ldap_servers_update_7106() {
  if (!ldap_servers_db_field_exists('ldap_servers', 'account_name_attr')) {
    db_add_field('ldap_servers', 'account_name_attr', [
      'description' => 'The attribute to be used as the account name if not the user_attr',
      'type' => 'varchar',
      'length' => 255,
      'not null' => FALSE,
      'default' => '',
    ]);
    $msg = t('"account_name_attr" field added to ldap_servers table');
  }

  return ($msg) ? $msg : t('No database changes made.');
}

/**
 * Remove allow_conflicting_drupal_accts from ldap_servers table.
 */
function ldap_servers_update_7107() {
  if (ldap_servers_db_field_exists('ldap_servers', 'allow_conflicting_drupal_accts')) {
    db_drop_field('ldap_servers', 'allow_conflicting_drupal_accts');
    $msg = t('"allow_conflicting_drupal_accts" field removed from ldap_servers table');
  }
  return ($msg) ? $msg : t('No database changes made.');
}

/**
 *
 */
function ldap_servers_db_field_exists($table, $field_name) {
  if (!db_field_exists($table, $field_name) && !db_field_exists($table, drupal_strtolower($field_name))) {
    return FALSE;
  }
  else {
    return TRUE;
  }
}

/**
 * Add group related fields to ldap_servers table.
 */
function ldap_servers_update_7108() {

  foreach (['groupFunctionalityUnused', 'groupNested', 'groupSearchAll', 'groupUserMembershipsAttrExists', 'groupDeriveFromDn', 'groupUserMembershipsAttrExists'] as $tinyint_field_name) {
    if (!ldap_servers_db_field_exists('ldap_servers', $tinyint_field_name)) {
      db_add_field('ldap_servers', $tinyint_field_name, [
        'type' => 'int',
        'size' => 'tiny',
        'not null' => FALSE,
        'default' => 0,
      ]);
      $msg = t('"!name" field added to ldap_servers table', ['!name' => $tinyint_field_name]);
    }
  }
  foreach (['groupUserMembershipsAttr', 'groupMembershipsAttr', 'groupTestGroupDn', 'groupUserMembershipsAttr', 'groupMembershipsAttrMatchingUserAttr'] as $varchar255field_name) {
    if (!ldap_servers_db_field_exists('ldap_servers', $varchar255field_name) && !ldap_servers_db_field_exists('ldap_servers', drupal_strtolower($varchar255field_name))) {
      db_add_field('ldap_servers', $varchar255field_name, [
        'type' => 'varchar',
        'length' => '255',
        'not null' => FALSE,
      ]);
      $msg = t('"!name" field added to ldap_servers table', ['!name' => $varchar255field_name]);
    }
  }
}

/**
 * Adjust group related fields to ldap_servers table.
 */
function ldap_servers_update_7109() {

  if (!ldap_servers_db_field_exists('ldap_servers', 'groupNested')) {
    db_add_field('ldap_servers', 'groupNested', [
      'type' => 'int',
      'size' => 'tiny',
      'not null' => FALSE,
      'default' => 0,
    ]);
    $msg = t('"groupNested" field added to ldap_servers table');
  }

  if (!ldap_servers_db_field_exists('ldap_servers', 'groupUseFirstAttr')) {
    db_add_field('ldap_servers', 'groupUseFirstAttr', [
      'type' => 'int',
      'size' => 'tiny',
      'not null' => FALSE,
      'default' => 0,
    ]);
    $msg .= '<br/>' . t('"groupUseFirstAttr" field added to ldap_servers table');
  }

  if (!ldap_servers_db_field_exists('ldap_servers', 'groupSearchAll')) {
    db_add_field('ldap_servers', 'groupSearchAll', [
      'type' => 'int',
      'size' => 'tiny',
      'not null' => FALSE,
      'default' => 0,
    ]);
    $msg = t('"groupSearchAll" field added to ldap_servers table');
  }

  if (!ldap_servers_db_field_exists('ldap_servers', 'groupUserMembershipsAttrExists')) {
    db_add_field('ldap_servers', 'groupUserMembershipsAttrExists', [
      'type' => 'int',
      'size' => 'tiny',
      'not null' => FALSE,
      'default' => 0,
    ]);
    $msg = t('"groupUserMembershipsAttrExists" field added to ldap_servers table');
  }

  if (!ldap_servers_db_field_exists('ldap_servers', 'groupUserMembershipsAttr')) {
    db_add_field('ldap_servers', 'groupUserMembershipsAttr', [
      'type' => 'varchar',
      'length' => '255',
      'not null' => FALSE,
    ]);
    $msg = t('"groupUserMembershipsAttr" field added to ldap_servers table');
  }

  if (!ldap_servers_db_field_exists('ldap_servers', 'groupMembershipsAttr')) {
    db_add_field('ldap_servers', 'groupMembershipsAttr', [
      'type' => 'varchar',
      'length' => '255',
      'not null' => FALSE,
    ]);
    $msg = t('"groupMembershipsAttr" field added to ldap_servers table');
  }

  if (!ldap_servers_db_field_exists('ldap_servers', 'groupMembershipsAttrMatchingUserAttr')) {
    db_add_field('ldap_servers', 'groupMembershipsAttrMatchingUserAttr', [
      'type' => 'varchar',
      'length' => '255',
      'not null' => FALSE,
    ]);
    $msg = t('"groupMembershipsAttrMatchingUserAttr" field added to ldap_servers table');
  }

  if (!ldap_servers_db_field_exists('ldap_servers', 'groupUserMembershipsAttrExists')) {
    db_add_field('ldap_servers', 'groupUserMembershipsAttrExists', [
      'type' => 'int',
      'size' => 'tiny',
      'not null' => FALSE,
      'default' => 0,
    ]);
    $msg = t('"groupUserMembershipsAttrExists" field added to ldap_servers table');
  }

  if (!ldap_servers_db_field_exists('ldap_servers', 'groupUserMembershipsAttr')) {
    db_add_field('ldap_servers', 'groupUserMembershipsAttr', [
      'type' => 'varchar',
      'length' => '255',
      'not null' => FALSE,
    ]);
    $msg = t('"groupUserMembershipsAttr" field added to ldap_servers table');
  }

}

/**
 * Adjust group related fields to ldap_servers table.
 */
function ldap_servers_update_7110() {

  if (!ldap_servers_db_field_exists('ldap_servers', 'groupFunctionalityUnused')) {
    db_add_field('ldap_servers', 'groupFunctionalityUnused', [
      'type' => 'int',
      'size' => 'tiny',
      'not null' => FALSE,
      'default' => 0,
    ]);
    $msg = t('"groupFunctionalityUnused" field added to ldap_servers table');
  }

  if (!ldap_servers_db_field_exists('ldap_servers', 'groupTestGroupDn')) {
    db_add_field('ldap_servers', 'groupTestGroupDn', [
      'type' => 'varchar',
      'length' => '255',
      'not null' => FALSE,
    ]);
    $msg = t('"groupTestGroupDn" field added to ldap_servers table');
  }

  if (!ldap_servers_db_field_exists('ldap_servers', 'groupTestGroupDnWriteable')) {
    db_add_field('ldap_servers', 'groupTestGroupDnWriteable', [
      'type' => 'varchar',
      'length' => '255',
      'not null' => FALSE,
    ]);
    $msg = t('"groupTestGroupDnWriteable" field added to ldap_servers table');
  }

}

/**
 * Add field groupTestGroupDnWriteable to ldap_servers table.
 */
function ldap_servers_update_7111() {

  if (!ldap_servers_db_field_exists('ldap_servers', 'groupTestGroupDnWriteable')) {
    db_add_field('ldap_servers', 'groupTestGroupDnWriteable', [
      'type' => 'varchar',
      'length' => '255',
      'not null' => FALSE,
    ]);
    $msg = t('"groupTestGroupDnWriteable" field added to ldap_servers table');
  }

}

/**
 * Add field testingDrupalUserDn to ldap_servers table.
 */
function ldap_servers_update_7112() {

  if (!ldap_servers_db_field_exists('ldap_servers', 'testingDrupalUserDn')) {
    db_add_field('ldap_servers', 'testingDrupalUserDn', [
      'type' => 'varchar',
      'length' => '255',
      'not null' => FALSE,
    ]);
    $msg = t('"testingDrupalUserDn" field added to ldap_servers table');
  }

}

/**
 * Upgrade as much as feasible for 7.1 to 7.2 branch.
 */
function ldap_servers_update_7201() {

  $change_log = [];

  // 1. ldap_user is now required for ldap_authentication and ldap_authorization.
  if (module_exists('ldap_authentication') || module_exists('ldap_authorization')) {
    module_enable(['ldap_user'], TRUE);
    $change_log[] = t('LDAP User Module Enabled');
  }

  /**
   * ldap_servers and ldap_authorization tables in 7.x-1.x to 7.x-2.x update
   *
   * LDAP_SERVERS fields that don't change:
   *  sid, numeric_sid, name, status, ldap_type, address, port, tls, bind_method,
   *  binding_service_acct, binddn, bindpw, basedn, user_attr, account_name_attr,
   *  mail_attr, mail_template, unique_persistent_attr, user_dn_expression,
   *  testing_drupal_username, group_object_category
   *  search_pagination, search_page_size, ldap_to_drupal_user,
   *
   * LDAP_SERVERS fields not populated in update:
   *   unique_persistent_attr_binary
   *   testingDrupalUserDn
   *   groupTestGroupDn - new no value in it and not important
   *   groupTestGroupDnWriteable - new no value in it and not important
   *
   * LDAP_SERVERS fields set/adjusted in update:
   *   groupNested
   *   groupFunctionalityUnused = 1 if ldap authorization tables exist
   *   groupDeriveFromDn from option IIA of ldap authorization
   *   groupDeriveFromDnAttr from option IIA of ldap authorization
   *   groupUserMembershipsAttrExists = 1 if option IIB used in ldap authorization
   *   groupUserMembershipsAttr  get from ldap authorization  IIB
   *   groupMembershipsAttr from option IIC in ldap authorization derive from entry
   *   groupMembershipsAttrMatchingUserAttr from option IIC
   *
   *
   * LDAP_AUTHORIZATION fields that don't change:
   *   numeric_consumer_conf_id, sid, consumer_type, consumer_module
   *   status, only_ldap_authenticated, mappings, use_filter,
   *   synchronization_modes, synchronization_actions, synch_to_ldap,
   *   synch_on_logon, revoke_ldap_provisioned, create_consumers,
   *   regrant_ldap_provisioned
   *
   * LDAP_AUTHORIZATION fields populated in update:
   *   useFirstAttrAsGroupId = derive_from_attr_use_first_attr || derive_from_entry_use_first_attr
   *
   * LDAP_AUTHORIZATION fields to remove in update
   *    derive_from_dn, derive_from_dn_attr, derive_from_entry, derive_from_attr
   *    derive_from_attr_attr, derive_from_entry, derive_from_entry_attr,
   *    derive_from_entry_entries_attr, derive_from_entry_nested,
   *    derive_from_attr_use_first_attr, derive_from_entry_search_all
   *    derive_from_entry_use_first_attr
   *
   */

  // 2.  add any missing fields from schema.
  ldap_servers_install_update_schema(ldap_servers_schema(), $change_log);
  if (module_exists('ldap_authorization')) {
    ldap_servers_install_update_schema(ldap_authorization_schema(), $change_log);
  }
  if (module_exists('ldap_query')) {
    ldap_servers_install_update_schema(ldap_query_schema(), $change_log);
  }

  // 3.  move configuration data that has changed location within ldap modules.
  $field_changes = [];
  $ldap_server_records = [];
  $select = db_select('ldap_servers')
    ->fields('ldap_servers')
    ->execute();
  foreach ($select as $record) {
    $ldap_server_records[$record->sid] = $record;
  }

  if (db_table_exists('ldap_authorization')) {
    $ldap_authorization_record = NULL;
    $select = db_select('ldap_authorization', 'authz')
      ->fields('authz')
      ->execute();
    // Pick best ldap authorization conf to use to configure ldap server.
    $max_weight = -1;
    foreach ($select as $record) {
      $weight = (int) ($record->status) + (int) ($record->consumer_type == 'drupal_role');
      if ($weight > $max_weight) {
        $max_weight = $weight;
        $ldap_authorization_record = $record;
      }
    }

    foreach ($ldap_server_records as $sid => $ldap_server_record) {
      if ($ldap_authorization_record && $ldap_authorization_record->sid == $sid) {
        $consumer_type = $ldap_authorization_record->consumer_type;
        $field_changes['ldap_servers'][$sid]['groupFunctionalityUnused'] = 0;
        if ($ldap_authorization_record->derive_from_dn) {
          $field_changes['ldap_servers'][$sid]['groupDeriveFromDn'] = 1;
          $field_changes['ldap_servers'][$sid]['groupDeriveFromDnAttr'] = $ldap_authorization_record->derive_from_dn_attr;
        }
        if ($ldap_authorization_record->derive_from_attr) {
          $field_changes['ldap_servers'][$sid]['groupUserMembershipsAttrExists'] = 1;
          $field_changes['ldap_servers'][$sid]['groupUserMembershipsAttr'] = $ldap_authorization_record->derive_from_attr_attr;
        }
        if ($ldap_authorization_record->derive_from_entry) {
          // Eg members.
          $field_changes['ldap_servers'][$sid]['groupMembershipsAttr'] = $ldap_authorization_record->derive_from_entry_attr;
          // Eg dn.
          $field_changes['ldap_servers'][$sid]['groupMembershipsAttrMatchingUserAttr'] = $ldap_authorization_record->derive_from_entry_entries_attr;
        }
        if ($ldap_authorization_record->derive_from_entry_nested) {
          $field_changes['ldap_servers'][$sid]['groupNested'] = 1;
        }
        if ($ldap_authorization_record->derive_from_attr_use_first_attr || $ldap_authorization_record->derive_from_entry_use_first_attr) {
          $field_changes['ldap_authorization'][$consumer_type]['useFirstAttrAsGroupId'] = 1;
        }
      }
      else {
        $field_changes['ldap_servers'][$sid]['groupFunctionalityUnused'] = 1;
      }
    }
  }

  foreach ($field_changes as $table_name => $record) {
    foreach ($record as $id => $field_data) {
      if ($table_name == 'ldap_servers' || $table_name == 'ldap_authorization') {
        $id_field_name = 'sid';
      }
      else {
        continue;
      }
      if (count($field_data)) {
        $change_log[] = t("!table_name where !id_field_name = !id values updated", [
          '!table_name' => $table_name,
          '!id_field_name' => $id_field_name,
          '!id' => $id,
        ]);
        $num_updated = db_update($table_name)
          ->fields($field_data)
          ->condition($id_field_name, $id, '=')
          ->execute();
      }
    }
  }

  // 4.  remove ldap_authorization fields that are unused.
  $ldap_authorization_fields_to_remove = [
    'derive_from_dn',
    'derive_from_dn_attr',
    'derive_from_attr',
    'derive_from_entry',
    'derive_from_attr_attr',
    'derive_from_entry_attr',
    'derive_from_entry_entries_attr',
    'derive_from_entry_nested',
    'derive_from_entry_search_all',
    'derive_from_entry_use_first_attr',
    'derive_from_attr_use_first_attr',
  ];

  foreach ($ldap_authorization_fields_to_remove as $ldap_authorization_field) {
    db_drop_field('ldap_authorization', $ldap_authorization_field);
  }
  $change_log[] = t("ldap_authorization table fields removed: !fields_removed", ['!fields_removed' => join(', ', $ldap_authorization_fields_to_remove)]);

  // 5. ldap_authentication and ldap_user changes are in variables, not tables.
  $ldap_authentication_conf_data = variable_get('ldap_authentication_conf', []);
  if (!is_array($ldap_authentication_conf_data['sids'])) {
    $ldap_authentication_conf_data['sids'] = [];
  }

  $ldap_user_conf_data = variable_get('ldap_user_conf', []);

  $ldap_authentication_sids = array_keys($ldap_authentication_conf_data['sids']);
  if (count($ldap_authentication_sids) == 1) {
    $ldap_user_conf_data['drupalAcctProvisionServer'] = $ldap_authentication_sids[0];
  }

  // Conflict log vs resolve moved from ldap_authentication to ldap_user.
  if (!empty($ldap_authentication_conf_data['authenticationMode'])) {
    if ($ldap_authentication_conf_data['loginConflictResolve'] == LDAP_AUTHENTICATION_CONFLICT_LOG) {
      $ldap_user_conf_data['userConflictResolve'] = LDAP_USER_CONFLICT_LOG;
      $change_log[] = t('ldap_authentication_conf -> userConflictResolve set to') . LDAP_USER_CONFLICT_LOG;
    }
    elseif ($ldap_authentication_conf_data['loginConflictResolve'] == LDAP_AUTHENTICATION_CONFLICT_RESOLVE) {
      $ldap_user_conf_data['userConflictResolve'] = LDAP_USER_CONFLICT_RESOLVE;
      $change_log[] = t('ldap_authentication_conf -> userConflictResolve set to') . LDAP_USER_CONFLICT_RESOLVE;
    }
    unset($ldap_authentication_conf_data['loginConflictResolve']);
    $change_log[] = t('ldap_authentication_conf -> loginConflictResolve value removed');
  }
  else {
    $ldap_user_conf_data['userConflictResolve'] = LDAP_USER_CONFLICT_RESOLVE_DEFAULT;
    $change_log[] = t('ldap_authentication_conf -> userConflictResolve set to') . LDAP_USER_CONFLICT_RESOLVE_DEFAULT;
  }

  if (isset($ldap_authentication_conf_data['acctCreation'])) {
    $ldap_user_conf_data['acctCreation'] = $ldap_authentication_conf_data['acctCreation'];
    $change_log[] = t('ldap_user_conf -> acctCreation set to value in ldap_authentication_conf -> acctCreation');
    unset($ldap_authentication_conf_data['acctCreation']);
    $change_log[] = t('ldap_authentication_conf -> acctCreation value removed');
  }
  else {
    $ldap_user_conf_data['acctCreation'] = LDAP_USER_ACCT_CREATION_LDAP_BEHAVIOR_DEFAULT;
    $change_log[] = t('ldap_user_conf -> acctCreation set to default:') . ' ' . LDAP_USER_ACCT_CREATION_LDAP_BEHAVIOR_DEFAULT;
  }

  $ldap_user_conf_data['manualAccountConflict'] = LDAP_USER_MANUAL_ACCT_CONFLICT_REJECT;
  $change_log[] = t('ldap_user_conf -> manualAccountConflict set to default:') . ' ' . LDAP_USER_MANUAL_ACCT_CONFLICT_REJECT;

  $change_log[] = t('LDAP User configuration populated.');
  $change_log[] = t('LDAP Authentication configuration updated.');
  variable_set('ldap_authentication_conf', $ldap_authentication_conf_data);
  variable_set('ldap_user_conf', $ldap_user_conf_data);

  $summary = '<h2>' . t('Please check through all the LDAP module configuration pages.
    The update from 7.x-1.x to 7.x-2.x is not automatable!  The configuration pages
    must be read through and configured.') . '</h2>' .
    theme('item_list', [
      'items' => $change_log,
      'type' => 'ul',
      'title' => 'Changes in 7.x-1.x to 7.x-2.x update',
    ]
    );

  watchdog('ldap_servers', $summary, [], WATCHDOG_INFO);
  return $summary;

}

/**
 * Make ldap_servers.bind_method field small int instead of tiny int for ctools bug.
 */
function ldap_servers_update_7202() {

  db_change_field('ldap_servers', 'bind_method', 'bind_method', [
    'type' => 'int',
    'size' => 'small',
    'not null' => TRUE,
    'default' => 0,
  ]);

}

/**
 * Make all schema field names lowercase in ldap server to deal with cronic case sensitivity issues.
 */
function ldap_servers_update_7203() {
  $schema = ldap_servers_schema();
  $changes = [
    'testingDrupalUserDn' => 'testing_drupal_user_dn',
    'group_object_category' => 'grp_object_cat',
    'groupFunctionalityUnused' => 'grp_unused',
    'groupNested' => 'grp_nested',
    'groupUserMembershipsAttrExists' => 'grp_user_memb_attr_exists',
    'groupUserMembershipsAttr' => 'grp_user_memb_attr',
    'groupMembershipsAttr' => 'grp_memb_attr',
    'groupMembershipsAttrMatchingUserAttr' => 'grp_memb_attr_match_user_attr',
    'groupDeriveFromDn' => 'grp_derive_from_dn',
    'groupDeriveFromDnAttr' => 'grp_derive_from_dn_attr',
    'groupTestGroupDn' => 'grp_test_grp_dn',
    'groupTestGroupDnWriteable' => 'grp_test_grp_dn_writeable',
  ];
  foreach ($changes as $old_field_name => $new_field_name) {
    $field_schema = $schema['ldap_servers']['fields'][$new_field_name];
    if (ldap_servers_db_field_exists('ldap_servers', $old_field_name)) {
      if (ldap_servers_db_field_exists('ldap_servers', $new_field_name)) {
        db_drop_field('ldap_servers', $old_field_name);
      }
      else {
        db_change_field('ldap_servers', $old_field_name, $new_field_name, $field_schema);
      }
    }
  }

}

/**
 * Add picture_attr field in schema.
 */
function ldap_servers_update_7204() {
  if (!ldap_servers_db_field_exists('ldap_servers', 'picture_attr')) {
    db_add_field(
      'ldap_servers',
      'picture_attr',
      [
        'type' => 'varchar',
        'length' => 255,
        'not null' => FALSE,
      ]
    );
  }
}

/**
 * Fix any double serialized ldap server basedns.
 */
function ldap_servers_update_7205() {

  module_load_include('inc', 'ldap_servers', 'ldap_servers.functions');
  $ldap_servers = ldap_servers_get_servers();
  foreach ($ldap_servers as $sid => $ldap_server) {
    if ($ldap_server->basedn && is_scalar($ldap_server->basedn)) {
      // These are still serialized after being loaded from db/ctools so were double serialized.
      $ldap_server->basedn = unserialize($ldap_server->basedn);
      $ldap_server->save();
    }
  }

}

/**
 * Add LDAP Referrals fields in schema.
 */
function ldap_servers_update_7206() {
  if (!ldap_servers_db_field_exists('ldap_servers', 'followrefs')) {
    db_add_field(
      'ldap_servers',
      'followrefs',
      [
        'type' => 'int',
        'size' => 'tiny',
        'not null' => FALSE,
        'default' => 0,
      ]
    );
  }
}

/**
 * Fixes a typo in an LDAP variable name.
 */
function ldap_servers_update_7207() {
  if (!is_null($old_var = variable_get('ldap_servers_require_ssl_for_credentails'))) {
    variable_set('ldap_servers_require_ssl_for_credentials', $old_var);
    variable_del('ldap_servers_require_ssl_for_credentails');
  }
}

/**
 * Removes HTTPS checking.
 */
function ldap_servers_update_7208() {
  variable_del('ldap_servers_require_ssl_for_credentials');
  return t('HTTPS validation was removed, if you need mixed mode consider another module such as securelogin for this. Mixed mode is strongly discouraged.');

}

/**
 *
 */
function ldap_servers_install_update_schema($schema, &$change_log) {
  foreach ($schema as $table_name => $table_schema) {
    foreach ($table_schema['fields'] as $field_name => $field_schema) {
      if (!ldap_servers_db_field_exists($table_name, $field_name)) {
        db_add_field($table_name, $field_name, $field_schema);
        $change_log[] = t("!field_name field added to !table_name table", ['!field_name' => $field_name, '!table_name' => $table_name]);
      }
    }
  }
}

/**
 * Change mcrypt to openssl.
 */
function ldap_servers_update_7209() {
  if (variable_get('ldap_servers_encryption') != LDAP_SERVERS_ENC_TYPE_CLEARTEXT) {
    variable_set('ldap_servers_encryption', LDAP_SERVERS_ENC_TYPE_OPENSSL);
    if (!extension_loaded('openssl')) {
      watchdog('ldap', 'Warning: OpenSSL missing, no alternative for encryption.');
    }
    return t('Encryption backend has changed, please re-enter your service account credentials.');
  }
}
