Files
plugi/extensions/plugi-ext-form/admin/Classes/SubmissionRateLimiter.php
T
deepDiverPaul 25030638a4 Implemented: editor uploads are constrained to safe image files inside
the upload tree, and public form submissions are
size-bounded and rate-limited
2026-11-30 16:51:15 +01:00

79 lines
2.5 KiB
PHP

<?php
namespace Plugi\Extensions\Form;
use RuntimeException;
class SubmissionRateLimiter
{
private const MAX_SUBMISSIONS = 5;
private const WINDOW_SECONDS = 600;
private $db;
private string $table;
public function __construct($db = null)
{
global $phpb_db;
$this->db = $db ?? $phpb_db ?? null;
$prefix = preg_replace('/[^a-zA-Z0-9_]/', '', $_ENV['DATABASE_PREFIX'] ?? '');
$this->table = '`' . $prefix . 'ext__form_submission_limits`';
}
public function consume(int $formId, string $clientIp): bool
{
if (!is_object($this->db)) {
throw new RuntimeException('The submission rate limit store is unavailable.');
}
$now = time();
$ipHash = hash('sha256', $clientIp);
if (!$this->db->query(
"INSERT IGNORE INTO {$this->table} (formId, ipHash, startedAt, submissions) VALUES (?, ?, ?, 0)",
[$formId, $ipHash, $now]
)) {
throw new RuntimeException('The submission rate limit could not be initialized.');
}
$allowed = $this->db->transaction(function () use ($formId, $ipHash, $now): bool {
$rows = $this->db->select(
"SELECT startedAt, submissions FROM {$this->table} WHERE formId = ? AND ipHash = ? FOR UPDATE",
[$formId, $ipHash]
);
if (empty($rows)) {
throw new RuntimeException('The submission rate limit could not be loaded.');
}
$startedAt = (int) $rows[0]['startedAt'];
$submissions = (int) $rows[0]['submissions'];
if ($now - $startedAt >= self::WINDOW_SECONDS) {
$startedAt = $now;
$submissions = 0;
}
if ($submissions >= self::MAX_SUBMISSIONS) {
return false;
}
if (!$this->db->query(
"UPDATE {$this->table} SET startedAt = ?, submissions = ? WHERE formId = ? AND ipHash = ?",
[$startedAt, $submissions + 1, $formId, $ipHash]
)) {
throw new RuntimeException('The submission rate limit could not be updated.');
}
return true;
});
if ($allowed && random_int(1, 100) === 1) {
try {
$this->db->query(
"DELETE FROM {$this->table} WHERE startedAt < ?",
[$now - (self::WINDOW_SECONDS * 2)]
);
} catch (\Throwable $exception) {
}
}
return $allowed;
}
}