Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions includes/class-webdecoy-cloud-connect.php
Original file line number Diff line number Diff line change
Expand Up @@ -123,13 +123,19 @@ public function handle_connect(): void
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- boolean presence only; nonce already verified above
$digest = !empty($_POST['digest']) ? '1' : '0';

// Which control started the flow, so the app can count connects by
// entry point. An allowlisted label, never free text.
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated -- allowlisted below; nonce already verified above
$source = self::connect_source(isset($_POST['source']) ? sanitize_key(wp_unslash($_POST['source'])) : '');

// Build the query with http_build_query so every value is encoded
// exactly once (WP's add_query_arg does not encode appended args).
$query = http_build_query([
'site_url' => home_url(),
'site_name' => get_bloginfo('name'),
'nonce' => $nonce,
'digest' => $digest,
'source' => $source,
'return_url' => admin_url('admin.php?page=webdecoy&tab=cloud&wd_connect=1'),
]);
$url = self::CONNECT_URL . '?' . $query;
Expand Down Expand Up @@ -403,6 +409,15 @@ public static function get_entitlements(): array
return self::normalize_entitlements(is_array($cached) ? $cached : [], time());
}

/**
* The entry point label sent with a connect: 'invite' for the activation
* notice, 'settings' for everything else.
*/
public static function connect_source(string $posted): string
{
return $posted === 'invite' ? 'invite' : 'settings';
}

/**
* Whether this site is connected to WebDecoy Cloud (an API key is stored).
*/
Expand Down
194 changes: 194 additions & 0 deletions includes/class-webdecoy-connect-invite.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
<?php
/**
* WebDecoy connect invite
*
* One dismissible notice that offers WebDecoy Cloud after the plugin is
* activated. Until now Connect lived on the Settings page's Cloud tab, and
* no site ever found it. The notice says what the plugin is already doing
* on this site, using this week's counts when there are any, then offers
* Connect with the same nonce-protected form the Cloud tab uses.
*
* Shown to administrators on the WordPress dashboard, the Plugins screen and
* WebDecoy's own pages, only while the site is not connected. "Not now"
* snoozes for 14 days; "Don't show again" ends it. Makes no external request:
* the plugin leaves the site only when the admin clicks Connect.
*
* State: option `webdecoy_connect_invite` — '' (pending), 'never', or
* 'later:<epoch>' (snoozed until then).
*
* @package WebDecoy
*/

// Prevent direct access.
if (!defined('ABSPATH')) {
exit;
}

/**
* WebDecoy connect invite controller.
*/
class WebDecoy_Connect_Invite
{
public const STATE_OPTION = 'webdecoy_connect_invite';

/** "Not now" snoozes for 14 days (literal to keep the class loadable sans WordPress). */
public const SNOOZE = 1209600;

/** Where the Connect click came from, sent to the app so it can count invite connects. */
public const SOURCE = 'invite';

private const ACTION = 'webdecoy_connect_invite';

/** Set once this request has rendered the invite, so the review ask can stand aside. */
private static bool $rendered = false;

public function register(): void
{
if (!is_admin() || WebDecoy_Runtime_Config::hide_admin_ui()) {
return;
}
// Ahead of the review ask (priority 10), which checks rendered().
add_action('admin_notices', [$this, 'render'], 5);
add_action('admin_post_' . self::ACTION, [$this, 'handle']);
}

/** Whether the invite was shown on this page view. */
public static function rendered(): bool
{
return self::$rendered;
}

public function render(): void
{
if (!current_user_can('manage_options') || !self::on_relevant_screen()) {
return;
}
$connected = class_exists('WebDecoy_Cloud_Connect') && WebDecoy_Cloud_Connect::is_connected();
if (!self::is_due($connected, (string) get_option(self::STATE_OPTION, ''), time())) {
return;
}
self::$rendered = true;

$visits = class_exists('WebDecoy_Crawler_Visits') ? WebDecoy_Crawler_Visits::summary(168) : ['total' => 0, 'groups' => ['ai' => 0]];
$total = (int) ($visits['total'] ?? 0);
$ai = (int) ($visits['groups']['ai'] ?? 0);

$link = static function (string $choice): string {
return wp_nonce_url(
admin_url('admin-post.php?action=' . self::ACTION . '&choice=' . $choice),
self::ACTION
);
};
?>
<div class="notice notice-info webdecoy-connect-invite">
<p>
<strong><?php esc_html_e('WebDecoy:', 'webdecoy'); ?></strong>
<?php echo esc_html(self::message($total, $ai)); ?>
</p>
<p><?php echo esc_html(self::offer()); ?></p>
<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
<input type="hidden" name="action" value="webdecoy_cloud_connect" />
<input type="hidden" name="source" value="<?php echo esc_attr(self::SOURCE); ?>" />
<?php wp_nonce_field('webdecoy_cloud_connect'); ?>
<p>
<label>
<input type="checkbox" name="digest" value="1" />
<?php esc_html_e('Send me a monthly security report', 'webdecoy'); ?>
</label>
</p>
<p>
<button type="submit" class="button button-primary">
<?php esc_html_e('Connect free', 'webdecoy'); ?>
</button>
<a href="<?php echo esc_url($link('later')); ?>" class="button">
<?php esc_html_e('Not now', 'webdecoy'); ?>
</a>
<a href="<?php echo esc_url($link('never')); ?>">
<?php esc_html_e("Don't show again", 'webdecoy'); ?>
</a>
</p>
</form>
</div>
<?php
}

/** Record "Not now" or "Don't show again" and return to the page. */
public function handle(): void
{
if (!current_user_can('manage_options')) {
wp_die(esc_html__('You do not have permission to do that.', 'webdecoy'), 403);
}
check_admin_referer(self::ACTION);

$choice = isset($_GET['choice']) ? sanitize_key(wp_unslash($_GET['choice'])) : '';
update_option(self::STATE_OPTION, self::state_for($choice, time()), false);

wp_safe_redirect(wp_get_referer() ?: admin_url());
exit;
}

private static function on_relevant_screen(): bool
{
if (!function_exists('get_current_screen')) {
return false;
}
$screen = get_current_screen();
if ($screen === null) {
return false;
}
$id = (string) $screen->id;
return $id === 'dashboard' || $id === 'plugins' || strpos($id, 'webdecoy') !== false;
}

// ---------------------------------------------------------------------
// Pure helpers (no WordPress calls) — unit-tested in tests/ConnectInviteTest.php.
// ---------------------------------------------------------------------

/** Whether to show the invite: not connected, not dismissed, not snoozed past now. */
public static function is_due(bool $connected, string $state, int $now): bool
{
if ($connected) {
return false;
}
if ($state === '') {
return true;
}
if (strpos($state, 'later:') === 0) {
return $now >= (int) substr($state, 6);
}
return false;
}

/** The stored state for a choice. Anything unrecognised snoozes rather than silencing it for good. */
public static function state_for(string $choice, int $now): string
{
return $choice === 'never' ? 'never' : 'later:' . ($now + self::SNOOZE);
}

/** What the plugin is doing on this site, from this week's counts. */
public static function message(int $total, int $ai): string
{
if ($total <= 0) {
return __('WebDecoy is now counting bot and AI crawler visits on this site. Everything it shows works without an account.', 'webdecoy');
}
if ($ai > 0) {
return sprintf(
/* translators: 1: bot visits counted in 7 days, 2: of which AI crawlers and agents */
__('In the last 7 days WebDecoy counted %1$s bot visits on this site, %2$s of them from AI crawlers and agents. Everything it shows works without an account.', 'webdecoy'),
number_format($total),
number_format($ai)
);
}
return sprintf(
/* translators: %s: bot visits counted in 7 days */
__('In the last 7 days WebDecoy counted %s bot visits on this site. Everything it shows works without an account.', 'webdecoy'),
number_format($total)
);
}

/** Why connect, in what a free connected site actually gets. */
public static function offer(): string
{
return __('Connect free to see each bot\'s history beside your detections and this site in the WebDecoy dashboard, with an optional monthly report. Nothing leaves your site until you click Connect.', 'webdecoy');
}
}
4 changes: 4 additions & 0 deletions includes/class-webdecoy-review-ask.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ public function render(): void
if (!current_user_can('manage_options') || !self::on_relevant_screen()) {
return;
}
// One ask per page view: the connect invite goes first when it shows.
if (class_exists('WebDecoy_Connect_Invite') && WebDecoy_Connect_Invite::rendered()) {
return;
}

$now = time();
$first_seen = (int) get_option(self::FIRST_SEEN_OPTION, 0);
Expand Down
66 changes: 66 additions & 0 deletions tests/ConnectInviteTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

declare(strict_types=1);

/**
* Tests for the pure helpers in WebDecoy_Connect_Invite: when the invite
* shows, what each choice stores, and the copy built on the week's counts.
*
* Run: php tests/run.php
*/

if (!defined('ABSPATH')) {
define('ABSPATH', '/tmp/');
}
require_once dirname(__DIR__) . '/includes/class-webdecoy-connect-invite.php';
require_once dirname(__DIR__) . '/includes/class-webdecoy-cloud-connect.php';

$t = ['TestRunner', 'test'];
$true = ['TestRunner', 'assertTrue'];
$same = ['TestRunner', 'assertSame'];

$now = 20000000;

echo "\nConnect invite: when it shows\n";

$t('shows on a site that is not connected and has not answered', function () use ($true, $now) {
$true(WebDecoy_Connect_Invite::is_due(false, '', $now) === true, 'pending, not connected -> shown');
});

$t('never on a connected site, whatever the state', function () use ($true, $now) {
$true(WebDecoy_Connect_Invite::is_due(true, '', $now) === false, 'connected -> hidden');
$true(WebDecoy_Connect_Invite::is_due(true, 'later:1', $now) === false, 'connected after a snooze -> hidden');
});

$t("don't show again ends it; a snooze holds until it ends", function () use ($true, $now) {
$true(WebDecoy_Connect_Invite::is_due(false, 'never', $now) === false, 'never -> hidden');
$true(WebDecoy_Connect_Invite::is_due(false, 'later:' . ($now + 1), $now) === false, 'inside the snooze -> hidden');
$true(WebDecoy_Connect_Invite::is_due(false, 'later:' . $now, $now) === true, 'snooze over -> shown');
});

echo "\nConnect invite: choices\n";

$t('not now snoozes 14 days; anything unrecognised snoozes too', function () use ($same, $now) {
$same('later:' . ($now + WebDecoy_Connect_Invite::SNOOZE), WebDecoy_Connect_Invite::state_for('later', $now));
$same('later:' . ($now + WebDecoy_Connect_Invite::SNOOZE), WebDecoy_Connect_Invite::state_for('bogus', $now));
$same('never', WebDecoy_Connect_Invite::state_for('never', $now));
});

$t('the connect source is an allowlisted label', function () use ($same) {
$same('invite', WebDecoy_Cloud_Connect::connect_source('invite'));
$same('settings', WebDecoy_Cloud_Connect::connect_source(''));
$same('settings', WebDecoy_Cloud_Connect::connect_source('<script>'));
});

echo "\nConnect invite: copy\n";

$t('names the week\'s counts when there are any', function () use ($true) {
$msg = WebDecoy_Connect_Invite::message(1234, 56);
$true(strpos($msg, '1,234 bot visits') !== false && strpos($msg, '56 of them') !== false, 'totals and AI share');
$true(strpos(WebDecoy_Connect_Invite::message(7, 0), '7 bot visits') !== false, 'totals without AI');
$true(strpos(WebDecoy_Connect_Invite::message(0, 0), 'now counting') !== false, 'nothing counted yet');
});

$t('promises nothing leaves the site before Connect', function () use ($true) {
$true(strpos(WebDecoy_Connect_Invite::offer(), 'Nothing leaves your site until you click Connect') !== false, 'privacy line');
});
6 changes: 6 additions & 0 deletions uninstall.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@
delete_option('webdecoy_critical_moment_last');
delete_option('webdecoy_cached_crawler_counts');
delete_option('webdecoy_cache_bypass_state');
delete_option('webdecoy_connect_invite');
delete_option('webdecoy_review_ask');
delete_option('webdecoy_review_first_seen');
delete_transient('webdecoy_llms_txt');

// Clear scheduled events
Expand Down Expand Up @@ -118,6 +121,9 @@
delete_option('webdecoy_critical_moment_last');
delete_option('webdecoy_cached_crawler_counts');
delete_option('webdecoy_cache_bypass_state');
delete_option('webdecoy_connect_invite');
delete_option('webdecoy_review_ask');
delete_option('webdecoy_review_first_seen');
delete_transient('webdecoy_llms_txt');

// Clear scheduled events for this site
Expand Down
5 changes: 5 additions & 0 deletions webdecoy.php
Original file line number Diff line number Diff line change
Expand Up @@ -1108,6 +1108,7 @@ public function load_includes(): void
require_once WEBDECOY_PLUGIN_DIR . 'includes/class-webdecoy-actor-feed.php';
require_once WEBDECOY_PLUGIN_DIR . 'includes/class-webdecoy-critical-moment.php';
require_once WEBDECOY_PLUGIN_DIR . 'includes/class-webdecoy-review-ask.php';
require_once WEBDECOY_PLUGIN_DIR . 'includes/class-webdecoy-connect-invite.php';

// One-click Cloud connect + entitlements sync. Makes no external request
// until the admin explicitly clicks "Connect".
Expand All @@ -1132,6 +1133,10 @@ public function load_includes(): void
// One wordpress.org review ask, after a week with bots counted. Admin only.
(new WebDecoy_Review_Ask())->register();

// One dismissible Connect offer while the site is not connected. Admin only;
// the review ask stands aside on a page view that shows it.
(new WebDecoy_Connect_Invite())->register();

// Automatic robots.txt: appends the chosen categories' agents to the
// virtual robots.txt. Adds nothing until the owner picks a category.
WebDecoy_Robots_Txt::register($this->options['robots_disallow_categories'] ?? []);
Expand Down
Loading