AutobanCommands.php in Automatic IP ban (Autoban) 8
File
src/Commands/AutobanCommands.php
View source
<?php
namespace Drupal\autoban\Commands;
use Drush\Commands\DrushCommands;
class AutobanCommands extends DrushCommands {
protected $autoban;
public function ban($rule = NULL) {
$this->autoban = \Drupal::service('autoban');
$autobanStorage = \Drupal::service('entity_type.manager')
->getStorage('autoban');
$this
->output()
->writeln('Autoban banning start...');
if (!empty($rule)) {
if (!$autobanStorage
->load($rule)) {
$this
->logger()
->error(sprintf('Wrong rule %s', $rule));
return;
}
$this
->output()
->writeln(sprintf('Ban for rule %s', $rule));
$banned = $this
->banRule($rule);
if ($banned > 0) {
$this
->logger()
->success(sprintf('Banned count: %s', $banned));
}
else {
$this
->logger()
->warning('No banned IP.');
}
}
else {
$rules = $autobanStorage
->loadMultiple();
$this
->output()
->writeln(sprintf('Ban for all rules: %s', count($rules)));
if (!empty($rules)) {
$totalBanned = 0;
foreach (array_keys($rules) as $rule) {
$banned = $this
->banRule($rule);
$this
->logger()
->notice(sprintf('Rule %s Banned count: %s', $rule, $banned));
$totalBanned += $banned;
}
if ($totalBanned > 0) {
$this
->logger()
->success(sprintf('Total banned IP count: %s', $totalBanned));
}
else {
$this
->logger()
->warning('No banned IP.');
}
}
}
$this
->output()
->writeln('Finished.');
}
private function banRule($rule) {
$bannedIp = $this->autoban
->getBannedIp($rule);
$banned = 0;
if ($bannedIp) {
$banned = $this->autoban
->banIpList($bannedIp, $rule);
}
return $banned;
}
}