<?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_credentails');
  variable_del('ldap_servers_encrypt_key');

}

/**
 * Implements hook_requirements().
 */
function ldap_servers_requirements($phase) {
  $requirements = array();

  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.
  return $requirements;
}

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

  $schema['ldap_servers'] = array(
    'export' => array(
      'key' => 'sid',
      'key name' => 'Server ID',
      'primary key' => 'numeric_sid',
      'identifier' => 'ldap_servers_conf',
      'api' => array(
        'owner' => 'ldap_servers',
        'api' => 'ldap_servers',
        'minimum_version' => 1,
        'current_version' => 1,
        ),
      ),
    'primary key' => array('numeric_sid'),
    'unique keys' => array('name' => array('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', array(
      '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',
    array(
      'type' => 'int',
      'size' => 'tiny',
      'not null' => FALSE,
      'default' => 0,
    )
  );

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

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

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

  db_change_field('ldap_servers', 'binddn', 'binddn', array(
    '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', array(
      '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', array(
      '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', array(
      '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', array(
      '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', array(
      '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(array('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', array(
    '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 (array('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, array(
        'type' => 'int',
        'size' => 'tiny',
        'not null' => FALSE,
        'default' => 0,
      ));
      $msg = t('"!name" field added to ldap_servers table', array('!name' => $tinyint_field_name));
    }
  }
  foreach (array('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, array(
        'type' => 'varchar',
        'length' => '255',
        'not null' => FALSE,
      ));
      $msg = t('"!name" field added to ldap_servers table', array('!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', array(
      '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', array(
      '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', array(
      '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', array(
      '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', array(
      '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', array(
      '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', array(
      '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', array(
      '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', array(
      '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', array(
      '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', array(
      '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', array(
      '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', array(
      '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', array(
      '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 = array();

  // 1. ldap_user is now required for ldap_authentication and ldap_authorization
  if (module_exists('ldap_authentication') || module_exists('ldap_authorization')) {
    module_enable(array('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 = array();
  $ldap_server_records = array();
  $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) {
          $field_changes['ldap_servers'][$sid]['groupMembershipsAttr'] = $ldap_authorization_record->derive_from_entry_attr; // eg members
          $field_changes['ldap_servers'][$sid]['groupMembershipsAttrMatchingUserAttr'] = $ldap_authorization_record->derive_from_entry_entries_attr; // eg dn
        }
        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", array(
          '!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 = array(
    '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", array('!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', array());
  $ldap_user_conf_data = variable_get('ldap_user_conf', array());

  $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', array(
      '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', array(
    '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 = array(
    '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',
      array(
        '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',
      array(
        'type' => 'int',
        'size' => 'tiny',
        'not null' => FALSE,
        'default' => 0,
      )
    );
  }
}

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", array('!field_name' => $field_name, '!table_name' => $table_name));
      }
    }
  }
}
