You are here

class HttpblWhitelistForm in http:BL 8

Displays banned IP addresses.

Hierarchy

Expanded class hierarchy of HttpblWhitelistForm

1 string reference to 'HttpblWhitelistForm'
httpbl.routing.yml in ./httpbl.routing.yml
httpbl.routing.yml

File

src/Form/HttpblWhitelistForm.php, line 16

Namespace

Drupal\httpbl\Form
View source
class HttpblWhitelistForm extends FormBase {

  /**
   * The Httpbl Evaluator.
   *
   * @var \Drupal\httpbl\HttpblEvaluatorInterface
   */
  protected $httpblEvaluator;

  /**
   * The Httpbl Response.
   *
   * @var \Drupal\httpbl\HttpblResponseInterface
   */
  protected $httpblResponse;

  /**
   * A logger arbitration instance.
   *
   * @var \Drupal\httpbl\Logger\HttpblLogTrapperInterface
   */
  protected $logTrapper;

  /**
   * White-list form services.
   *
   * @param \Drupal\httpbl\HttpblEvaluatorInterface         $httpblEvaluator
   * @param \Drupal\httpbl\HttpblResponseInterface          $httpblResponse
   * @param \Drupal\httpbl\Logger\HttpblLogTrapperInterface $logTrapper
   */
  public function __construct(HttpblEvaluatorInterface $httpblEvaluator, HttpblResponseInterface $httpblResponse, HttpblLogTrapperInterface $logTrapper) {
    $this->httpblEvaluator = $httpblEvaluator;
    $this->httpblResponse = $httpblResponse;
    $this->logTrapper = $logTrapper;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('httpbl.evaluator'), $container
      ->get('httpbl.response'), $container
      ->get('httpbl.logtrapper'));
  }

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

  /**
   * {@inheritdoc}
   *
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['advise'] = array(
      '#markup' => '<div class="httpbl-advice form-item">' . $this
        ->t('Please note:  Session white-listing requires cookies to be enabled.') . '</div>',
    );
    $form['reason'] = array(
      '#type' => 'textarea',
      '#title' => t('Reason you were blocked. (It\'s okay to say you don\'t know if you don\'t)'),
      '#size' => 60,
      '#required' => TRUE,
    );
    $form['block'] = array(
      '#type' => 'textfield',
      '#title' => t('LEAVE THIS BLANK! (This is where robotic spammers fail, because they don\'t actually read!)'),
      '#size' => 15,
    );
    $form['leave'] = array(
      '#type' => 'textfield',
      '#size' => 30,
      '#attributes' => array(
        'style' => 'display: none',
      ),
    );
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('White-list request'),
    );

    // Save incoming original destination as a hidden form value.
    // This has never worked.  Need a new approach.
    // @todo - Figure out a way to return visitor to original request if they
    // pass the challenge.
    $form['arrival'] = array(
      '#type' => 'hidden',
    );
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $ip = $this
      ->getRequest()
      ->getClientIP();
    $project_link = $this->httpblEvaluator
      ->projectLink($ip);
    $values = $form_state
      ->getValues();

    // If the forbidden areas have any value, visitor has failed the challenge.
    if ($values['block'] || $values['leave']) {

      // Kill any white-listed session for this visitor.
      if (isset($_SESSION['httpbl_status'])) {
        unset($_SESSION['httpbl_status']);
      }

      // If we are storing visitor lookup results...
      if (\Drupal::state()
        ->get('httpbl.storage') == HTTPBL_DB_HH || \Drupal::state()
        ->get('httpbl.storage') == HTTPBL_DB_HH_DRUPAL) {

        // Update them from greylisted to blacklisted (they will also be auto-
        // banned or not, per configuration option).
        $this->httpblEvaluator
          ->updateIpLocalStatus($ip, HTTPBL_LIST_BLACK, $offset = \Drupal::state()
          ->get('httpbl.blacklist_offset'));
        \Drupal::state()
          ->get('httpbl.blacklist_offset');

        // Get the blacklist date offset and prepare a readable date interval for
        // a message to user.
        $offset = \Drupal::state()
          ->get('httpbl.blacklist_offset');
        $return_date = \Drupal::service('date.formatter')
          ->formatInterval($offset, $granularity = 2, $langcode = NULL);

        // Log the visitor failure.

        //$this->logTrapper->trapNotice('@ip blacklisted for @return_date for failing session white-list challenge.', ['@ip' => $ip, '@return_date' => $return_date]);
        $this->logTrapper
          ->trapNotice('@ip blacklisted for @return_date for failing session white-list challenge. Source: @source.', [
          '@ip' => $ip,
          '@return_date' => $return_date,
          '@source' => HTTPBL_CHALLENGE_FAILURE,
          'link' => $project_link,
        ]);

        // Build failed/blacklisted response to visitor.  It will say how long
        // they've been blacklisted for (the configured amount of time).
        $failureResponse = $this->httpblResponse
          ->challengeFailureBlacklisted($ip, $return_date);
        print $failureResponse;

        // Buh-bye!
        exit;
      }
      else {

        // Not storing visitor lookups.  Visitor will remain greylisted (per
        // Project Honepot results) and in white-list challenge purgatory. So,
        // simply inform them of the failure.
        $this->logTrapper
          ->trapWarning('@ip failed session white-list request.  Source: @source.', [
          '@ip' => $ip,
          '@source' => HTTPBL_CHALLENGE_FAILURE,
          'link' => $project_link,
        ]);
        $failureResponse = $this->httpblResponse
          ->challengeFailurePurgatory();
        print $failureResponse;
        exit;
      }
    }

    // This challenge was a success.  Visitor will be session white-listed on submit.
    $this->logTrapper
      ->trapNotice('@ip success at white-list challenge. Source: @source.', [
      '@ip' => $ip,
      '@source' => HTTPBL_CHALLENGE_SUCCESS,
      'link' => $project_link,
    ]);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Unset the White-list Challenge
    if (isset($_SESSION['httpbl_challenge'])) {
      unset($_SESSION['httpbl_challenge']);
    }

    // Set this visitor as Session White-listed
    $_SESSION['httpbl_status'] = 'session_whitelisted';
    drupal_set_message(t('Success! Your current session has been white-listed.'), 'status', FALSE);

    // Setup redirect to original request Uri
    $url = Url::fromRoute('<front>');
    $form_state
      ->setRedirectUrl($url);
  }

}

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.
HttpblWhitelistForm::$httpblEvaluator protected property The Httpbl Evaluator.
HttpblWhitelistForm::$httpblResponse protected property The Httpbl Response.
HttpblWhitelistForm::$logTrapper protected property A logger arbitration instance.
HttpblWhitelistForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
HttpblWhitelistForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
HttpblWhitelistForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
HttpblWhitelistForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
HttpblWhitelistForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
HttpblWhitelistForm::__construct public function White-list form services.
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.