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; } }