You are here

class HostForm in http:BL 8

Form controller for the host entity Add/Edit form.

Hierarchy

Expanded class hierarchy of HostForm

File

src/Form/HostForm.php, line 20

Namespace

Drupal\httpbl\Form
View source
class HostForm extends ContentEntityForm {

  /**
   * The ban IP manager.
   *
   * @var \Drupal\ban\BanIpManagerInterface
   */
  protected $banManager;

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

  /**
   * Constructs a HostForm object with additional services.
   *
   * @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
   *   The entity repository service.
   * @param \Drupal\ban\BanIpManagerInterface $banManager
   *   The Ban manager.
   * @param \Drupal\httpbl\Logger\HttpblLogTrapperInterface $logTrapper
   *   The log manager.
   * @param \Drupal\Component\Datetime\TimeInterface $time
   *   The time service (for tracking changes).
   */
  public function __construct(EntityRepositoryInterface $entity_repository, BanIpManagerInterface $banManager, HttpblLogTrapperInterface $logTrapper, TimeInterface $time = NULL) {
    parent::__construct($entity_repository, NULL, $time);
    $this->banManager = $banManager;
    $this->logTrapper = $logTrapper;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity.repository'), $container
      ->get('ban.ip_manager'), $container
      ->get('httpbl.logtrapper'), $container
      ->get('datetime.time'));
  }

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

    /* @var $entity \Drupal\httpbl\Entity\Host */
    $form = parent::buildForm($form, $form_state);
    $entity = $this->entity;
    $form['langcode'] = array(
      '#title' => $this
        ->t('Language'),
      '#type' => 'language_select',
      '#default_value' => $entity
        ->getUntranslated()
        ->language()
        ->getId(),
      '#languages' => Language::STATE_ALL,
    );
    $form['edit'] = array(
      '#type' => 'details',
      '#title' => t('Edit Http:BL Host'),
      '#description' => t('Add / Edit an Http:BL host.'),
      '#open' => TRUE,
    );
    $form['edit']['host_ip'] = array(
      '#title' => $this
        ->t('Host IP'),
      '#type' => 'textfield',
      '#size' => 15,
      '#default_value' => $entity->host_ip->value,
      '#maxlength' => 15,
      '#required' => TRUE,
    );

    // Get the expiry offset variables and prepare expiration values.
    $safeOffset = \Drupal::state()
      ->get('httpbl.safe_offset');
    $greyOffset = \Drupal::state()
      ->get('httpbl.greylist_offset');
    $blackOffset = \Drupal::state()
      ->get('httpbl.blacklist_offset');
    $safeExpires = \Drupal::service('date.formatter')
      ->formatTimeDiffUntil($safeOffset + \Drupal::time()
      ->getRequestTime());
    $greyExpires = \Drupal::service('date.formatter')
      ->formatTimeDiffUntil($greyOffset + \Drupal::time()
      ->getRequestTime());
    $blackExpires = \Drupal::service('date.formatter')
      ->formatTimeDiffUntil($blackOffset + \Drupal::time()
      ->getRequestTime());

    // Show the current expiration options associated with each status.
    $form['edit']['host_status'] = array(
      '#title' => $this
        ->t('Host Status'),
      '#type' => 'select',
      '#options' => [
        0 => $this
          ->t('White-listed - Expires in ' . $safeExpires),
        2 => $this
          ->t('Grey-listed - Expires in ' . $greyExpires),
        1 => $this
          ->t('Blacklisted - Expires in ' . $blackExpires),
      ],
      '#default_value' => $entity->host_status->value,
      '#description' => $this
        ->t('Uses expiry times configured in here.'),
      '#required' => TRUE,
    );

    // Advise the user on current state of storage settings.
    if ($storage = \Drupal::state()
      ->get('httpbl.storage') == HTTPBL_DB_HH_DRUPAL) {
      $form['edit']['explain_auto'] = array(
        '#title' => $this
          ->t('Auto-banning is enabled for Blacklisted hosts.  Blacklisting a host will add it to core Ban_ip.'),
        '#type' => 'item',
      );
    }
    else {
      $form['edit']['explain_auto'] = array(
        '#title' => $this
          ->t('Auto banning is NOT enabled for blacklisted hosts.'),
        '#type' => 'item',
      );
    }
    return $form;
  }

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

    /* @var $host \Drupal\httpbl\Entity\Host */
    $host = parent::buildEntity($form, $form_state);
    $values = $form_state
      ->getValues();

    // Get the current route so we can check whether we are adding or editing.
    $route = \Drupal::service('current_route_match')
      ->getCurrentRouteMatch()
      ->getRouteName();

    // If adding a host and the host already exists, don't allow duplicates.
    if ($route == 'httpbl.host_add' && HostQuery::getHostsByIp($values['host_ip'])) {
      $form_state
        ->setErrorByName('duplicate_host_attempt', $this
        ->t('Host @ip already exists!', array(
        '@ip' => $values['host_ip'],
      )));
    }
    $safeOffset = \Drupal::state()
      ->get('httpbl.safe_offset');
    $greyOffset = \Drupal::state()
      ->get('httpbl.greylist_offset');
    $blackOffset = \Drupal::state()
      ->get('httpbl.blacklist_offset');
    $safeExpiry = $safeOffset + \Drupal::time()
      ->getRequestTime();
    $greyExpiry = $greyOffset + \Drupal::time()
      ->getRequestTime();
    $blackExpiry = $blackOffset + \Drupal::time()
      ->getRequestTime();
    switch ($values['host_status']) {
      case '0':
        $host
          ->setExpiry($safeExpiry);
        break;
      case '1':
        $host
          ->setExpiry($blackExpiry);
        break;
      case '2':
        $host
          ->setExpiry($greyExpiry);
        break;
    }

    //$host->setSource(HTTPBL_ADMIN_SOURCE);
    return $host;
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $form_state
      ->setRedirect('entity.host.collection');
    $entity = $this
      ->getEntity();
    $previous_source = $entity
      ->getSource();
    $entity
      ->setSource(HTTPBL_ADMIN_SOURCE);
    $entity
      ->save();

    // Get the IP being added or edited.
    $ip = $entity->host_ip->value;

    // Get the user who added / edited this.
    $user = $this
      ->currentUser();
    $user = $user
      ->getDisplayName();

    // Get the storage state (whether we are saving host entities only or also to core Ban_ip for banning blacklisted IPs).
    $storage = \Drupal::state()
      ->get('httpbl.storage');

    // Get the current route so we can check whether we are adding or editing.
    $route = \Drupal::service('current_route_match')
      ->getCurrentRouteMatch()
      ->getRouteName();

    // If this is an edit it could be a status change for an IP previously banned.
    if ($route == 'entity.host.edit_form' && $entity->host_status->value != HTTPBL_LIST_BLACK && $this->banManager
      ->isBanned($ip)) {

      //Unban this IP.
      $this->banManager
        ->unbanIp($ip);

      // Log and message this unbanning.
      $this->logTrapper
        ->trapWarning('A banned @type has been un-banned: @title, by user @user. Previous evaluation source: @source.', array(
        '@type' => $this->entity
          ->bundle(),
        '@title' => $this->entity
          ->label(),
        '@user' => $user,
        '@source' => $previous_source,
        'link' => $entity
          ->projectLink(),
      ));
      drupal_set_message($this
        ->t('Previously banned host @ip has been unbanned.', array(
        '@ip' => $entity->host_ip->value,
      )), 'warning');
    }

    // @todo, do better separation of add and edit.
    // If Blacklisted & Banning...
    if ($entity->host_status->value == HTTPBL_LIST_BLACK && $storage == HTTPBL_DB_HH_DRUPAL) {

      // Ban the IP!
      $this->banManager
        ->banIp($ip);

      // Log this banning.
      if ($route == 'httpbl.host_add') {
        $this->logTrapper
          ->trapNotice('@type: added blacklisted and banned @title: by user @user. Source:@source.', array(
          '@type' => $this->entity
            ->bundle(),
          '@title' => $this->entity
            ->label(),
          '@user' => $user,
          '@source' => $this->entity
            ->getSource(),
          'link' => $entity
            ->projectLink(),
        ));
      }
      else {
        $this->logTrapper
          ->trapNotice('@type: updated blacklisted and banned @title: by user @user. Previous source: @source.', array(
          '@type' => $this->entity
            ->bundle(),
          '@title' => $this->entity
            ->label(),
          '@user' => $user,
          '@source' => $previous_source,
          'link' => $entity
            ->projectLink(),
        ));
      }
      drupal_set_message($this
        ->t('Host @ip was blacklisted and banned.', array(
        '@ip' => $entity->host_ip->value,
      )));
    }
    else {

      // Otherwise, log the edit that was made.
      $this->logTrapper
        ->trapNotice('Evaluated @type edited: @title, by user @user. Previous source: @source.', array(
        '@type' => $this->entity
          ->bundle(),
        '@title' => $this->entity
          ->label(),
        '@user' => $user,
        '@source' => $previous_source,
        'link' => $entity
          ->projectLink(),
      ));
    }
    $form_state
      ->setRedirect('entity.host.collection');
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ContentEntityForm::$entity protected property The entity being used by this form. Overrides EntityForm::$entity 9
ContentEntityForm::$entityRepository protected property The entity repository service.
ContentEntityForm::$entityTypeBundleInfo protected property The entity type bundle info service.
ContentEntityForm::$time protected property The time service.
ContentEntityForm::addRevisionableFormFields protected function Add revision form fields if the entity enabled the UI.
ContentEntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties Overrides EntityForm::copyFormValuesToEntity
ContentEntityForm::flagViolations protected function Flags violations for the current form. 4
ContentEntityForm::form public function Gets the actual form array to be built. Overrides EntityForm::form 13
ContentEntityForm::getBundleEntity protected function Returns the bundle entity of the entity, or NULL if there is none.
ContentEntityForm::getEditedFieldNames protected function Gets the names of all fields edited in the form. 4
ContentEntityForm::getFormDisplay public function Gets the form display. Overrides ContentEntityFormInterface::getFormDisplay
ContentEntityForm::getFormLangcode public function Gets the code identifying the active form language. Overrides ContentEntityFormInterface::getFormLangcode
ContentEntityForm::getNewRevisionDefault protected function Should new revisions created on default.
ContentEntityForm::init protected function Initializes the form state and the entity before the first form build. Overrides EntityForm::init 1
ContentEntityForm::initFormLangcodes protected function Initializes form language code values.
ContentEntityForm::isDefaultFormLangcode public function Checks whether the current form language matches the entity one. Overrides ContentEntityFormInterface::isDefaultFormLangcode
ContentEntityForm::prepareEntity protected function Prepares the entity object before the form is built first. Overrides EntityForm::prepareEntity 1
ContentEntityForm::setFormDisplay public function Sets the form display. Overrides ContentEntityFormInterface::setFormDisplay
ContentEntityForm::showRevisionUi protected function Checks whether the revision form fields should be added to the form.
ContentEntityForm::submitForm public function This is the default entity object builder function. It is called before any other submit handler to build the new entity object to be used by the following submit handlers. At this point of the form workflow the entity is validated and the form state… Overrides EntityForm::submitForm 3
ContentEntityForm::updateChangedTime public function Updates the changed time of the entity.
ContentEntityForm::updateFormLangcode public function Updates the form language to reflect any change to the entity language.
ContentEntityForm::validateForm public function Button-level validation handlers are highly discouraged for entity forms, as they will prevent entity validation from running. If the entity is going to be saved during the form submission, this method should be manually invoked from the button-level… Overrides FormBase::validateForm 3
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
EntityForm::$entityTypeManager protected property The entity type manager. 3
EntityForm::$moduleHandler protected property The module handler service.
EntityForm::$operation protected property The name of the current operation.
EntityForm::$privateEntityManager private property The entity manager.
EntityForm::actions protected function Returns an array of supported actions for the current entity form. 29
EntityForm::actionsElement protected function Returns the action form element for the current entity form.
EntityForm::afterBuild public function Form element #after_build callback: Updates the entity with submitted data.
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 5
EntityForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
EntityForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 1
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 10
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityManager public function Sets the entity manager for this form. Overrides EntityFormInterface::setEntityManager
EntityForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
EntityForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
EntityForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
EntityForm::__get public function
EntityForm::__set public function
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.
HostForm::$banManager protected property The ban IP manager.
HostForm::$logTrapper protected property A logger arbitration instance.
HostForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides ContentEntityForm::buildEntity
HostForm::buildForm public function Form constructor. Overrides EntityForm::buildForm
HostForm::create public static function Instantiates a new instance of this class. Overrides ContentEntityForm::create
HostForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
HostForm::__construct public function Constructs a HostForm object with additional services. Overrides ContentEntityForm::__construct
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.