You are here

AnonymousPublishingClAdminSpam.php in Anonymous Publishing 8

File

modules/anonymous_publishing_cl/src/Form/AnonymousPublishingClAdminSpam.php
View source
<?php

namespace Drupal\anonymous_publishing_cl\Form;

use Drupal\Core\Database\Connection;
use Drupal\Core\Datetime\DateFormatter;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Symfony\Component\DependencyInjection\ContainerInterface;
class AnonymousPublishingClAdminSpam extends FormBase {

  /**
   * The database connection service.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $database;

  /**
   * The database connection service.
   *
   * @var \Drupal\Core\Datetime\DateFormatter
   */
  protected $dateFormatter;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('database'), $container
      ->get('date.formatter'));
  }

  /**
   * Constructs a \Drupal\anonymous_publishing_cl\Form\AnonymousPublishingClAdminModeration object.
   *
   * @param \Drupal\Core\Database\Connection $database
   *   The database connection service.
   * @param \Drupal\Core\Datetime\DateFormatter
   *   The date formatter service.
   */
  public function __construct(Connection $database, DateFormatter $date_formatter) {
    $this->database = $database;
    $this->dateFormatter = $date_formatter;
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'anonymous_publishing_cl_admin_spam';
  }
  public function buildForm(array $form, FormStateInterface $form_state) {
    if (\Drupal::moduleHandler()
      ->moduleExists('ban')) {

      // Build an 'Update options' form.
      $form['options'] = array(
        '#type' => 'details',
        '#title' => $this
          ->t('Update options'),
        '#open' => TRUE,
        '#attributes' => array(
          'class' => array(
            'container-inline',
          ),
        ),
      );
      $options = array(
        'block' => $this
          ->t("Block the IP address"),
        'unblock' => $this
          ->t("Unblock the IP address"),
      );
      $form['options']['operation'] = array(
        '#type' => 'select',
        '#title' => $this
          ->t('Action'),
        '#title_display' => 'invisible',
        '#options' => $options,
        '#default_value' => 'publish',
      );
      $form['options']['submit'] = array(
        '#type' => 'submit',
        '#value' => $this
          ->t('Update'),
      );
    }
    else {
      $form['options'] = array(
        '#markup' => '<p><b>' . $this
          ->t("You can't ban IPs if you don't enable the BAN module.") . '</b></p>',
      );
    }
    $form['apu_info'] = [
      '#markup' => t("<p>The following table shows the IP-addresses and the average hits per day generated by the ten most aggressive spambots hitting the site. To move the bot's IP-address to Drupal's <code>{blocked_ips}</code> table, check the corresponding item line and Update using the proper action.</p><p>As an alternative to the Drupal <code>{blocked_ips}</code> table you may instead deny access to unwanted IP-addresses using the appropriate command in the web server access file.</p>"),
    ];
    $header = array(
      'ip' => array(
        'data' => $this
          ->t('IP-address'),
      ),
      'first' => array(
        'data' => $this
          ->t('First seen'),
      ),
      'last' => array(
        'data' => $this
          ->t('Last seeb'),
      ),
      'visits' => array(
        'data' => $this
          ->t('Total hits'),
      ),
      'freq' => array(
        'data' => $this
          ->t('Daily hits'),
      ),
      'status' => array(
        'data' => $this
          ->t('Status'),
      ),
      'blocked' => array(
        'data' => $this
          ->t('Banned'),
      ),
    );
    $options = array();
    $hidden_values = array();

    // Fetch first 10 bot reports.
    $rows = $this
      ->getAllSpamContents();

    // Build the table.
    foreach ($rows as $row) {
      $freq = $row->visits / ((\Drupal::time()
        ->getRequestTime() - $row->first) / 86400);
      $freq = min([
        $freq,
        $row->visits,
      ]);
      $options[$row->id] = array(
        'ip' => array(
          'data' => array(
            '#markup' => $row->ip,
          ),
        ),
        'first' => array(
          'data' => array(
            '#markup' => $this->dateFormatter
              ->formatInterval(\Drupal::time()
              ->getRequestTime() - $row->first, 1) . ' ' . t('ago'),
          ),
        ),
        'last' => array(
          'data' => array(
            '#markup' => $this->dateFormatter
              ->formatInterval(\Drupal::time()
              ->getRequestTime() - $row->last, 1) . ' ' . t('ago'),
          ),
        ),
        'visits' => array(
          'data' => array(
            '#markup' => $row->visits,
          ),
        ),
        'freq' => array(
          'data' => array(
            '#markup' => round($freq),
          ),
        ),
        'status' => array(
          'data' => array(
            '#markup' => round($freq),
          ),
        ),
        'blocked' => array(
          'data' => array(
            '#markup' => isset($row->iid) ? $this
              ->t('IP is banned') : $this
              ->t('IP is not banned'),
          ),
        ),
      );
      $hidden_values[$row->id] = $row->ip;
    }
    $form['hidden_values'] = array(
      '#type' => 'hidden',
      '#value' => serialize($hidden_values),
    );
    $form['items'] = array(
      '#type' => 'tableselect',
      '#header' => $header,
      '#options' => $options,
      '#empty' => $this
        ->t('There is no unverified content.'),
    );
    $form['pager'] = array(
      '#type' => 'pager',
    );
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $form_state
      ->setValue('items', array_diff($form_state
      ->getValue('items'), array(
      0,
    )));

    // We can't execute any 'Update options' if no items were selected.
    if (count($form_state
      ->getValue('items')) == 0) {
      $form_state
        ->setErrorByName('', $this
        ->t('Select one or more items to perform the update on.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $operation = $form_state
      ->getValue('operation');
    $ids = $form_state
      ->getValue('items');
    $hidden = unserialize($form_state
      ->getValue('hidden_values'));
    foreach ($ids as $id) {
      if ($operation = 'ban') {
        $existp = $this->database
          ->select('ban_ip')
          ->fields('blocked_ips')
          ->condition('ip', $hidden[$id])
          ->execute()
          ->fetchAssoc();
        if (FALSE == $existp) {
          $this->database
            ->insert('ban_ip')
            ->fields(array(
            'ip',
          ), array(
            $hidden[$id],
          ))
            ->execute();
        }
      }
      if ($operation == 'unban') {
        $this->database
          ->delete('ban_ip')
          ->condition('ip', $hidden[$id])
          ->execute();
      }
    }
    $this
      ->messenger()
      ->addMessage($this
      ->t('The update has been performed.'));
  }

  /**
   * Get all contents to moderate.
   *
   * @param int $test_id
   *   The test_id to retrieve results of.
   *
   * @return array
   *  Array of results grouped by test_class.
   */
  protected function getAllSpamContents() {
    $query = $this->database
      ->select('anonymous_publishing_bots', 'a');
    $query
      ->fields('a');
    if (\Drupal::moduleHandler()
      ->moduleExists('ban')) {
      $query
        ->join('ban_ip', 'b', 'a.ip = b.ip');
    }
    $query
      ->orderBy('a.visits');
    $query
      ->range(0, 10);
    return $query
      ->execute()
      ->fetchAll();
  }

}

Classes