3 namespace Drupal\ban\Form;
5 use Drupal\Core\Form\FormBase;
6 use Drupal\ban\BanIpManagerInterface;
7 use Drupal\Core\Form\FormStateInterface;
9 use Symfony\Component\DependencyInjection\ContainerInterface;
12 * Displays banned IP addresses.
14 class BanAdmin extends FormBase {
17 * @var \Drupal\ban\BanIpManagerInterface
22 * Constructs a new BanAdmin object.
24 * @param \Drupal\ban\BanIpManagerInterface $ip_manager
26 public function __construct(BanIpManagerInterface $ip_manager) {
27 $this->ipManager = $ip_manager;
33 public static function create(ContainerInterface $container) {
35 $container->get('ban.ip_manager')
42 public function getFormId() {
49 * @param string $default_ip
50 * (optional) IP address to be passed on to
51 * \Drupal::formBuilder()->getForm() for use as the default value of the IP
54 public function buildForm(array $form, FormStateInterface $form_state, $default_ip = '') {
56 $header = [$this->t('banned IP addresses'), $this->t('Operations')];
57 $result = $this->ipManager->findAll();
58 foreach ($result as $ip) {
63 'title' => $this->t('Delete'),
64 'url' => Url::fromRoute('ban.delete', ['ban_id' => $ip->iid]),
68 '#type' => 'operations',
76 '#title' => $this->t('IP address'),
77 '#type' => 'textfield',
80 '#default_value' => $default_ip,
81 '#description' => $this->t('Enter a valid IP address.'),
83 $form['actions'] = ['#type' => 'actions'];
84 $form['actions']['submit'] = [
86 '#value' => $this->t('Add'),
89 $form['ban_ip_banning_table'] = [
93 '#empty' => $this->t('No blocked IP addresses available.'),
102 public function validateForm(array &$form, FormStateInterface $form_state) {
103 $ip = trim($form_state->getValue('ip'));
104 if ($this->ipManager->isBanned($ip)) {
105 $form_state->setErrorByName('ip', $this->t('This IP address is already banned.'));
107 elseif ($ip == $this->getRequest()->getClientIP()) {
108 $form_state->setErrorByName('ip', $this->t('You may not ban your own IP address.'));
110 elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE) == FALSE) {
111 $form_state->setErrorByName('ip', $this->t('Enter a valid IP address.'));
118 public function submitForm(array &$form, FormStateInterface $form_state) {
119 $ip = trim($form_state->getValue('ip'));
120 $this->ipManager->banIp($ip);
121 drupal_set_message($this->t('The IP address %ip has been banned.', ['%ip' => $ip]));
122 $form_state->setRedirect('ban.admin_page');