You are here

class LdapUserTestForm in Lightweight Directory Access Protocol (LDAP) 8.3

Same name and namespace in other branches
  1. 8.4 ldap_user/src/Form/LdapUserTestForm.php \Drupal\ldap_user\Form\LdapUserTestForm

A form to allow the administrator to query LDAP.

Hierarchy

Expanded class hierarchy of LdapUserTestForm

1 string reference to 'LdapUserTestForm'
ldap_user.routing.yml in ldap_user/ldap_user.routing.yml
ldap_user/ldap_user.routing.yml

File

ldap_user/src/Form/LdapUserTestForm.php, line 21

Namespace

Drupal\ldap_user\Form
View source
class LdapUserTestForm extends FormBase implements LdapUserAttributesInterface {
  private static $syncTriggerOptions;
  protected $request;
  protected $serverFactory;
  protected $entityTypeManager;

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

  /**
   * {@inheritdoc}
   */
  public function __construct(RequestStack $request_stack, ServerFactory $server_factory, EntityTypeManagerInterface $entity_type_manager) {
    $this->request = $request_stack
      ->getCurrentRequest();
    $this->serverFactory = $server_factory;
    $this->entityTypeManager = $entity_type_manager;
    self::$syncTriggerOptions = [
      self::PROVISION_DRUPAL_USER_ON_USER_UPDATE_CREATE => $this
        ->t('On sync to Drupal user create or update. Requires a server with binding method of "Service Account Bind" or "Anonymous Bind".'),
      self::PROVISION_DRUPAL_USER_ON_USER_AUTHENTICATION => $this
        ->t('On create or sync to Drupal user when successfully authenticated with LDAP credentials. (Requires LDAP Authentication module).'),
      self::PROVISION_DRUPAL_USER_ON_USER_ON_MANUAL_CREATION => $this
        ->t('On manual creation of Drupal user from admin/people/create and "Create corresponding LDAP entry" is checked'),
      self::PROVISION_LDAP_ENTRY_ON_USER_ON_USER_UPDATE_CREATE => $this
        ->t('On creation or sync of an LDAP entry when a Drupal account is created or updated. Only applied to accounts with a status of approved.'),
      self::PROVISION_LDAP_ENTRY_ON_USER_ON_USER_AUTHENTICATION => $this
        ->t('On creation or sync of an LDAP entry when a user authenticates.'),
      self::PROVISION_LDAP_ENTRY_ON_USER_ON_USER_DELETE => $this
        ->t('On deletion of an LDAP entry when the corresponding Drupal Account is deleted.  This only applies when the LDAP entry was provisioned by Drupal by the LDAP User module.'),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('request_stack'), $container
      ->get('ldap.servers'), $container
      ->get('entity_type.manager'));
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $op = NULL) {
    $form['#prefix'] = $this
      ->t('<h1>Debug LDAP synchronization events</h1>');
    $form['usage'] = [
      '#markup' => $this
        ->t("This form is for debugging issues with specific provisioning events. If you want to test your setup in general, try the server's test page first."),
    ];
    $form['warning'] = [
      '#markup' => '<h3>' . $this
        ->t('If you trigger the event this will modify your data.') . '</h3>' . $this
        ->t('When in doubt, always work on a staging environment.'),
    ];
    $form['testing_drupal_username'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Testing Drupal Username'),
      '#default_value' => $this->request->query
        ->get('username'),
      '#required' => 1,
      '#size' => 30,
      '#maxlength' => 255,
      '#description' => $this
        ->t("The user need not exist in Drupal and testing will not affect the user's LDAP or Drupal Account."),
    ];
    $form['action'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Actions/Event Handler to Test'),
      '#required' => 0,
      '#default_value' => $this->request->query
        ->get('action'),
      '#options' => self::$syncTriggerOptions,
      '#required' => TRUE,
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Test'),
      '#weight' => 100,
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $username = $form_state
      ->getValue([
      'testing_drupal_username',
    ]);
    $selected_action = $form_state
      ->getValue([
      'action',
    ]);
    $config = $this
      ->configFactory()
      ->get('ldap_user.settings')
      ->get();
    $processor = new DrupalUserProcessor();
    $ldapProcessor = new LdapUserProcessor();
    $user_ldap_entry = FALSE;
    if ($config['drupalAcctProvisionServer']) {
      $user_ldap_entry = $this->serverFactory
        ->getUserDataFromServerByIdentifier($username, $config['drupalAcctProvisionServer']);
    }
    if ($config['ldapEntryProvisionServer']) {
      if (!$user_ldap_entry) {
        $user_ldap_entry = $this->serverFactory
          ->getUserDataFromServerByIdentifier($username, $config['ldapEntryProvisionServer']);
      }
    }
    $results = [];
    $results['username'] = $username;
    $results['related LDAP entry (before provisioning or syncing)'] = $user_ldap_entry;

    /** @var \Drupal\user\Entity\User $account */
    $existingAccount = $this->entityTypeManager
      ->getStorage('user')
      ->loadByProperties([
      'name' => $username,
    ]);
    $existingAccount = $existingAccount ? reset($existingAccount) : FALSE;
    if ($existingAccount) {
      $results['user entity (before provisioning or syncing)'] = $existingAccount
        ->toArray();
      $results['User Authmap'] = ExternalAuthenticationHelper::getUserIdentifierFromMap($existingAccount
        ->id());
    }
    else {
      $results['User Authmap'] = 'No authmaps available.  Authmaps only shown if user account exists beforehand';
    }
    $account = [
      'name' => $username,
    ];
    $sync_trigger_description = self::$syncTriggerOptions[$selected_action];
    foreach ([
      self::PROVISION_TO_DRUPAL,
      self::PROVISION_TO_LDAP,
    ] as $direction) {
      if ($this
        ->provisionEnabled($direction, $selected_action)) {
        if ($direction == self::PROVISION_TO_DRUPAL) {
          $processor
            ->provisionDrupalAccount($account);
          $results['provisionDrupalAccount method results']["context = {$sync_trigger_description}"]['proposed'] = $account;
        }
        else {
          $provision_result = $ldapProcessor
            ->provisionLdapEntry($username, NULL);
          $results['provisionLdapEntry method results']["context = {$sync_trigger_description}"] = $provision_result;
        }
      }
      else {
        if ($direction == self::PROVISION_TO_DRUPAL) {
          $results['provisionDrupalAccount method results']["context = {$sync_trigger_description}"] = 'Not enabled.';
        }
        else {
          $results['provisionLdapEntry method results']["context = {$sync_trigger_description}"] = 'Not enabled.';
        }
      }
    }
    if (function_exists('dpm')) {
      dpm($results);
    }
    else {
      drupal_set_message($this
        ->t('This form will not display results unless the devel module is enabled.'), 'warning');
    }
    $params = [
      'action' => $selected_action,
      'username' => $username,
    ];
    $form_state
      ->setRedirectUrl(Url::fromRoute('ldap_user.test_form', $params));
  }

  /**
   * Given a $prov_event determine if LDAP user configuration supports it.
   *
   * This is overall, not a per field syncing configuration.
   *
   * @param int $direction
   *   self::PROVISION_TO_DRUPAL or self::PROVISION_TO_LDAP.
   * @param int $provision_trigger
   *   Provision trigger, see events above, such as 'sync', 'provision',
   *   'delete_ldap_entry', 'delete_drupal_entry', 'cancel_drupal_entry'.
   *
   * @deprecated
   *
   * @return bool
   *   Provisioning enabled.
   *   TODO: Move to ldapusertestform and/or kill.
   */
  private function provisionEnabled($direction, $provision_trigger) {
    $result = FALSE;
    if ($direction == self::PROVISION_TO_LDAP) {
      $result = LdapConfiguration::provisionAvailableToLdap($provision_trigger);
    }
    elseif ($direction == self::PROVISION_TO_DRUPAL) {
      $result = LdapConfiguration::provisionAvailableToDrupal($provision_trigger);
    }
    return $result;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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::config protected function Retrieves a configuration object.
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
LdapUserAttributesInterface::ACCOUNT_CREATION_LDAP_BEHAVIOUR constant
LdapUserAttributesInterface::ACCOUNT_CREATION_USER_SETTINGS_FOR_LDAP constant
LdapUserAttributesInterface::EVENT_CREATE_DRUPAL_USER constant
LdapUserAttributesInterface::EVENT_CREATE_LDAP_ENTRY constant
LdapUserAttributesInterface::EVENT_LDAP_ASSOCIATE_DRUPAL_USER constant
LdapUserAttributesInterface::EVENT_SYNC_TO_DRUPAL_USER constant
LdapUserAttributesInterface::EVENT_SYNC_TO_LDAP_ENTRY constant
LdapUserAttributesInterface::MANUAL_ACCOUNT_CONFLICT_LDAP_ASSOCIATE constant
LdapUserAttributesInterface::MANUAL_ACCOUNT_CONFLICT_NO_LDAP_ASSOCIATE constant
LdapUserAttributesInterface::MANUAL_ACCOUNT_CONFLICT_REJECT constant
LdapUserAttributesInterface::MANUAL_ACCOUNT_CONFLICT_SHOW_OPTION_ON_FORM constant
LdapUserAttributesInterface::PROVISION_DRUPAL_USER_ON_USER_AUTHENTICATION constant
LdapUserAttributesInterface::PROVISION_DRUPAL_USER_ON_USER_ON_MANUAL_CREATION constant
LdapUserAttributesInterface::PROVISION_DRUPAL_USER_ON_USER_UPDATE_CREATE constant
LdapUserAttributesInterface::PROVISION_LDAP_ENTRY_ON_USER_ON_USER_AUTHENTICATION constant
LdapUserAttributesInterface::PROVISION_LDAP_ENTRY_ON_USER_ON_USER_DELETE constant
LdapUserAttributesInterface::PROVISION_LDAP_ENTRY_ON_USER_ON_USER_UPDATE_CREATE constant
LdapUserAttributesInterface::PROVISION_TO_ALL constant
LdapUserAttributesInterface::PROVISION_TO_DRUPAL constant
LdapUserAttributesInterface::PROVISION_TO_LDAP constant
LdapUserAttributesInterface::PROVISION_TO_NONE constant
LdapUserAttributesInterface::USER_CONFLICT_ATTEMPT_RESOLVE constant
LdapUserAttributesInterface::USER_CONFLICT_LOG constant
LdapUserTestForm::$entityTypeManager protected property
LdapUserTestForm::$request protected property
LdapUserTestForm::$serverFactory protected property
LdapUserTestForm::$syncTriggerOptions private static property
LdapUserTestForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
LdapUserTestForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
LdapUserTestForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
LdapUserTestForm::provisionEnabled private function Given a $prov_event determine if LDAP user configuration supports it.
LdapUserTestForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
LdapUserTestForm::__construct public function
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.
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.