From e825e7aac52f52c81b32db4a39cc8304d6a5d1a3 Mon Sep 17 00:00:00 2001 From: Zankaria Date: Sat, 25 May 2024 00:32:44 +0200 Subject: [PATCH] Add dynamic captcha support --- inc/config.php | 9 +++++++++ post.php | 2 +- templates/main.js | 30 ++++++++++++++++++++++++++++++ templates/post_form.html | 4 ++++ 4 files changed, 44 insertions(+), 1 deletion(-) diff --git a/inc/config.php b/inc/config.php index 319bb8fd..79181790 100644 --- a/inc/config.php +++ b/inc/config.php @@ -351,6 +351,15 @@ //); $config['simple_spam'] = false; + /* + * If not flase, the captcha is dynamically injected on the client if the web server set the `captcha-required` + * cookie to 1. The configuration value should be set the IP for which the captcha should be verified. + * + * Example: + * $config['dynamic_captcha'] = '127.0.0.1'; // Verify the captcha for users sending posts from the loopback address. + */ + $config['dynamic_captcha'] = false; + // Enable reCaptcha to make spam even harder. Rarely necessary. $config['recaptcha'] = false; diff --git a/post.php b/post.php index 644ff111..a7f7e88b 100644 --- a/post.php +++ b/post.php @@ -648,7 +648,7 @@ if (isset($_POST['delete'])) { } } // Remote 3rd party captchas. - else { + else if (!$config['dynamic_captcha'] || $config['dynamic_captcha'] === $_SERVER['REMOTE_ADDR']) { // recaptcha if ($config['recaptcha']) { if (!isset($_POST['g-recaptcha-response'])) { diff --git a/templates/main.js b/templates/main.js index a850787f..e0819622 100644 --- a/templates/main.js +++ b/templates/main.js @@ -222,6 +222,36 @@ function getCookie(cookie_name) { } } +{% endraw %} +{% if config.dynamic_captcha %} +function is_dynamic_captcha_enabled() { + let cookie = get_cookie('require-captcha'); + return cookie === '1'; +} + +function get_captcha_pub_key() { +{% if config.recaptcha %} + return "{{ config.recaptcha_public }}"; +{% else %} + return null; +{% endif %} +} + +function init_dynamic_captcha() { + if (!is_dynamic_captcha_enabled()) { + let pub_key = get_captcha_pub_key(); + if (!pub_key) { + console.error("Missing public captcha key!"); + return; + } + + let captcha_hook = document.getElementById('captcha'); + captcha_hook.style = ""; + } +} +{% endif %} +{% raw %} + function highlightReply(id) { if (typeof window.event != "undefined" && event.which == 2) { // don't highlight on middle click diff --git a/templates/post_form.html b/templates/post_form.html index 5a6854cf..8220107b 100644 --- a/templates/post_form.html +++ b/templates/post_form.html @@ -73,7 +73,11 @@ {% if config.recaptcha %} + {% if config.dynamic_captcha %} + + {% else %} + {% endif %} {% trans %}Verification{% endtrans %} {{ antibot.html() }}