You are here

class SimpleLdapUserSettingsForm in Simple LDAP 8

Hierarchy

Expanded class hierarchy of SimpleLdapUserSettingsForm

1 string reference to 'SimpleLdapUserSettingsForm'
simple_ldap_user.routing.yml in modules/simple_ldap_user/simple_ldap_user.routing.yml
modules/simple_ldap_user/simple_ldap_user.routing.yml

File

modules/simple_ldap_user/src/Form/SimpleLdapUserSettingsForm.php, line 14

Namespace

Drupal\simple_ldap_user\Form
View source
class SimpleLdapUserSettingsForm extends ConfigFormBase {

  /**
   * @var SimpleLdapServer
   */
  protected $server;

  /**
   * @var SimpleLdapServerSchema
   */
  protected $schema;

  /**
   * {@inheritdoc}
   *
   * Overwrite default constructor so we can also grab the server.
   */
  public function __construct(ConfigFactoryInterface $config_factory) {
    parent::__construct($config_factory);
    $this->server = \Drupal::service('simple_ldap.server');
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'simple_ldap_user_settings';
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'simple_ldap.user',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this
      ->config('simple_ldap.user');

    // Only display the form if we have a successful binding.
    if ($this->server
      ->bind()) {
      $this->schema = \Drupal::service('simple_ldap.schema');
      $object_classes = $this
        ->getObjectClassOptions();
      $schema_defaults = $this->schema
        ->getDefaultAttributeSettings();
      $selected_object_classes = $config
        ->get('object_class') ? $config
        ->get('object_class') : $schema_defaults['object_class'];

      // If this is Active Directory, we lock the main attribute options.
      $readonly = $this->server
        ->getServerType() == 'Active Directory' ? TRUE : FALSE;
      if ($readonly) {
        $this
          ->messenger()
          ->addWarning($this
          ->t('Your server is Active Directory, so some settings have been disabled.'));
      }

      // If there is user input via an ajax callback, set it here
      $selected_object_classes = $form_state
        ->getValue('object_class') ? $form_state
        ->getValue('object_class') : $selected_object_classes;
      $form['users'] = array(
        '#type' => 'fieldset',
        '#title' => $this
          ->t('LDAP Users'),
        '#open' => TRUE,
      );
      $form['users']['basedn'] = array(
        '#type' => 'textfield',
        '#title' => $this
          ->t('Base DN'),
        '#description' => $this
          ->t('The Base DN that will be searched for user accounts. Ex: dc=example,dc=com'),
        '#required' => TRUE,
        '#default_value' => $config
          ->get('basedn'),
      );
      $form['users']['user_scope'] = array(
        '#type' => 'radios',
        '#title' => $this
          ->t('Search scope'),
        '#options' => array(
          'sub' => $this
            ->t('Subtree') . ' - ' . t('Search the base DN and all of its children for user accounts.'),
          'one' => $this
            ->t('One-level') . ' - ' . t('Do not include children of the base DN while searching for user accounts.'),
        ),
        '#required' => TRUE,
        '#default_value' => $config
          ->get('user_scope'),
      );
      $form['users']['object_class'] = array(
        '#type' => 'select',
        '#title' => $this
          ->t('User ObjectClass'),
        '#options' => $object_classes,
        '#default_value' => $selected_object_classes,
        '#required' => TRUE,
        '#multiple' => TRUE,
        '#size' => 10,
        '#description' => $this
          ->t('Which LDAP objectClass should be used when searching for a user. This also determines which attributes you have available to map below.'),
        '#ajax' => array(
          'callback' => array(
            $this,
            'populateObjectClassAttributes',
          ),
          'wrapper' => 'user-attribute-mapping-wrapper',
        ),
        '#disabled' => $readonly,
      );
      $attributes = $this
        ->getAttributeOptions($selected_object_classes);
      $form['users']['attribute_mapping'] = array(
        '#type' => 'container',
        '#attributes' => array(
          'id' => 'user-attribute-mapping-wrapper',
        ),
      );

      // @TODO Use a Schema object to pull all attributes as options, and use select forms for these attributes
      $form['users']['attribute_mapping']['name_attribute'] = array(
        '#type' => 'select',
        '#title' => t('Username attribute'),
        '#options' => $attributes,
        '#required' => TRUE,
        '#description' => $this
          ->t('Which LDAP attribute should be mapped to a Drupal username. This is commonly "cn" or "uid".'),
        '#default_value' => $config
          ->get('name_attribute') ? $config
          ->get('name_attribute') : $schema_defaults['name_attribute'],
        '#disabled' => $readonly,
      );
      $form['users']['attribute_mapping']['mail_attribute'] = array(
        '#type' => 'select',
        '#title' => t('Mail attribute'),
        '#options' => $attributes,
        '#required' => TRUE,
        '#description' => $this
          ->t('Which LDAP attribute should be mapped to a Drupal email. This is commonly "mail".'),
        '#default_value' => $config
          ->get('mail_attribute') ? $config
          ->get('mail_attribute') : $schema_defaults['mail_attribute'],
        '#disabled' => $readonly,
      );
      $frequencies = [
        86400 => t('Every day'),
        21600 => t('Every 6 hours'),
        3600 => t('Every hour'),
        0 => t('Every cron run'),
      ];
      $form['users']['cron_frequency'] = array(
        '#type' => 'select',
        '#title' => t('Cron frequency'),
        '#options' => $frequencies,
        '#required' => TRUE,
        '#description' => $this
          ->t('How frequently should active/blocked users be checked against the LDAP server? This value is only checked when cron runs, so the frequency is constrained by how frequently cron runs.'),
        '#default_value' => $config
          ->get('cron_frequency') ? $config
          ->get('cron_frequency') : 0,
        '#disabled' => $readonly,
      );
    }
    else {
      $this
        ->messenger()
        ->addWarning($this
        ->t('There is a problem with your LDAP Server connection. As a result, this form has been disabled. Please <a href="@url">check your settings</a>.', array(
        '@url' => Url::fromRoute('simple_ldap.server')
          ->toString(),
      )));
    }
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = $this
      ->configFactory()
      ->getEditable('simple_ldap.user');
    $config
      ->set('basedn', $form_state
      ->getValue('basedn'))
      ->set('user_scope', $form_state
      ->getValue('user_scope'))
      ->set('object_class', $form_state
      ->getValue('object_class'))
      ->set('name_attribute', $form_state
      ->getValue('name_attribute'))
      ->set('mail_attribute', $form_state
      ->getValue('mail_attribute'))
      ->set('cron_frequency', $form_state
      ->getValue('cron_frequency'))
      ->save();
    parent::submitForm($form, $form_state);
  }

  /**
   * @return array
   *  A array of objectClasses formatted for use as options in a Form API element.
   */
  private function getObjectClassOptions() {
    $object_classes = $this->schema
      ->getSchemaItem('objectClasses');
    foreach ($object_classes as $key => $object_class) {
      $object_classes[$key] = $object_class['name'];
    }
    asort($object_classes);
    return $object_classes;
  }

  /**
   * @param array $object_classes
   *  A list of LDAP objectClasses.
   *
   * @return array
   *  A array of objectClass attributes formatted for use as options in a Form API element.
   */
  private function getAttributeOptions($object_classes) {
    $attributes = array();
    foreach ($object_classes as $object_class) {
      try {
        $result = $this->schema
          ->getAttributesByObjectClass($object_class);
        foreach ($result as $attribute) {
          $attributes[mb_strtolower($attribute)] = $attribute;
        }
      } catch (SimpleLdapException $e) {

        // Just absorb. No attributes are added to the list.
      }
    }
    asort($attributes);
    return $attributes;
  }

  /**
   * Ajax callback for the object_class element.
   */
  public function populateObjectClassAttributes(array &$form, FormStateInterface $form_state) {
    return array(
      $form['users']['attribute_mapping'],
    );
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBase::create public static function Instantiates a new instance of this class. Overrides FormBase::create 13
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
SimpleLdapUserSettingsForm::$schema protected property
SimpleLdapUserSettingsForm::$server protected property
SimpleLdapUserSettingsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
SimpleLdapUserSettingsForm::getAttributeOptions private function
SimpleLdapUserSettingsForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
SimpleLdapUserSettingsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
SimpleLdapUserSettingsForm::getObjectClassOptions private function
SimpleLdapUserSettingsForm::populateObjectClassAttributes public function Ajax callback for the object_class element.
SimpleLdapUserSettingsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
SimpleLdapUserSettingsForm::__construct public function Overwrite default constructor so we can also grab the server. Overrides ConfigFormBase::__construct
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.