40 private array $list = [];
42 private bool $enabled =
true;
44 public function __construct(
48 public function isEnabled() :
bool{
49 return $this->enabled;
52 public function setEnabled(
bool $flag) :
void{
53 $this->enabled = $flag;
56 public function getEntry(
string $name) : ?
BanEntry{
57 $this->removeExpired();
59 return $this->list[strtolower($name)] ??
null;
66 $this->removeExpired();
71 public function isBanned(
string $name) : bool{
72 $name = strtolower($name);
73 if(!$this->isEnabled()){
76 $this->removeExpired();
78 return isset($this->list[$name]);
82 public function add(BanEntry $entry) : void{
83 $this->list[$entry->getName()] = $entry;
87 public function addBan(
string $target, ?
string $reason =
null, ?\DateTime $expires =
null, ?
string $source =
null) : BanEntry{
88 $entry = new BanEntry($target);
89 $entry->setSource($source ?? $entry->getSource());
90 $entry->setExpires($expires);
91 $entry->setReason($reason ?? $entry->getReason());
93 $this->list[$entry->getName()] = $entry;
99 public function remove(
string $name) :
void{
100 $name = strtolower($name);
101 if(isset($this->list[$name])){
102 unset($this->list[$name]);
107 public function removeExpired() : void{
108 foreach(Utils::promoteKeys($this->list) as $name => $entry){
109 if($entry->hasExpired()){
110 unset($this->list[$name]);
115 public function load() : void{
117 $fp = @fopen($this->file,
"r");
118 if(is_resource($fp)){
119 while(($line = fgets($fp)) !==
false){
120 if($line[0] !==
"#"){
122 $entry = BanEntry::fromString($line);
124 $this->list[$entry->getName()] = $entry;
126 }
catch(\RuntimeException $e){
127 $logger = \GlobalLogger::get();
128 $logger->critical(
"Failed to parse ban entry from string \"" . trim($line) .
"\": " . $e->getMessage());
135 \GlobalLogger::get()->error(
"Could not load ban list");
139 public function save(
bool $writeHeader =
true) : void{
140 $this->removeExpired();
141 $fp = @fopen($this->file,
"w");
142 if(is_resource($fp)){
144 fwrite($fp,
"# victim name | ban date | banned by | banned until | reason\n\n");
147 foreach($this->list as $entry){
148 fwrite($fp, $entry->getString() .
"\n");
152 \GlobalLogger::get()->error(
"Could not save ban list");