SearchQueries.php: add
This commit is contained in:
parent
5bc1009dfb
commit
79f1c6ee38
1 changed files with 59 additions and 0 deletions
59
inc/Data/SearchQueries.php
Normal file
59
inc/Data/SearchQueries.php
Normal file
|
@ -0,0 +1,59 @@
|
|||
<?php
|
||||
namespace Vichan\Data;
|
||||
|
||||
|
||||
class SearchQueries {
|
||||
private \PDO $pdo;
|
||||
private int $queries_per_minutes_single;
|
||||
private int $queries_per_minutes_all;
|
||||
|
||||
private function checkFloodImpl(string $ip, string $phrase): bool {
|
||||
$now = time();
|
||||
|
||||
$query = $this->pdo->prepare("SELECT COUNT(*) FROM `search_queries` WHERE `ip` = :ip AND `time` > :time");
|
||||
$query->bindValue(':ip', $ip);
|
||||
$query->bindValue(':time', $now - ($this->queries_per_minutes_single * 60));
|
||||
$query->execute();
|
||||
if ($query->fetchColumn() > $this->queries_per_minutes_single) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$query = $this->pdo->prepare("SELECT COUNT(*) FROM `search_queries` WHERE `time` > :time");
|
||||
$query->bindValue(':time', $now - ($this->queries_per_minutes_all * 60));
|
||||
$query->execute();
|
||||
if ($query->fetchColumn() > $this->queries_per_minutes_all) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$query = $this->pdo->prepare("INSERT INTO `search_queries` VALUES (:ip, :time, :query)");
|
||||
$query->bindValue(':ip', $ip);
|
||||
$query->bindValue(':time', $now);
|
||||
$query->bindValue(':query', $phrase);
|
||||
$query->execute();
|
||||
|
||||
// Cleanup search queries table
|
||||
$query = prepare("DELETE FROM `search_queries` WHERE `time` <= :time");
|
||||
$query->bindValue(':time', time() - ($this->queries_per_minutes_all * 60));
|
||||
$query->execute();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function __construct(\PDO $pdo, int $queries_per_minutes_single, int $queries_per_minutes_all) {
|
||||
$this->pdo = $pdo;
|
||||
$this->queries_per_minutes_single = $queries_per_minutes_single;
|
||||
$this->queries_per_minutes_all = $queries_per_minutes_all;
|
||||
}
|
||||
|
||||
public function checkFlood(string $ip, string $phrase): bool {
|
||||
$this->pdo->beginTransaction();
|
||||
try {
|
||||
$ret = $this->checkFloodImpl($ip, $phrase);
|
||||
$this->pdo->commit();
|
||||
return $ret;
|
||||
} catch (\Exception $e) {
|
||||
$this->pdo->rollBack();
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue