Selfcap: overview (totals, chart, log), IP rules and settings. */ class Selfcap_Admin { private const SLUG = 'selfcap'; /** Rows per page in the verification log. The admin's last choice is remembered. */ private const PER_PAGE_OPTIONS = [10, 25, 50]; private const PER_PAGE_DEFAULT = 10; private const PER_PAGE_META = 'selfcap_per_page'; private const RANGES = [7, 30, 90]; public static function register(): void { add_action('admin_menu', [self::class, 'menu']); add_action('admin_init', [self::class, 'settings']); add_action('admin_enqueue_scripts', [self::class, 'assets']); add_action('admin_post_selfcap_add_rule', [self::class, 'add_rule']); add_action('admin_post_selfcap_delete_rule', [self::class, 'delete_rule']); add_filter('plugin_action_links_'.plugin_basename(SELFCAP_FILE), [self::class, 'action_links']); } public static function menu(): void { add_menu_page('Selfcap', 'Selfcap', 'manage_options', self::SLUG, [self::class, 'page'], 'dashicons-shield', 81); } public static function assets(string $hook): void { if ($hook !== 'toplevel_page_'.self::SLUG) { return; } $base = plugin_dir_url(SELFCAP_FILE).'assets/'; wp_enqueue_style('selfcap-admin', $base.'admin.css', [], SELFCAP_VERSION); wp_enqueue_script('selfcap-admin', $base.'admin.js', [], SELFCAP_VERSION, ['in_footer' => true]); } public static function action_links(array $links): array { array_unshift($links, ''.esc_html__('Settings', 'selfcap').''); return $links; } public static function settings(): void { register_setting('selfcap', Selfcap_Plugin::OPTION, ['sanitize_callback' => [self::class, 'sanitize']]); } public static function sanitize($input): array { $input = is_array($input) ? $input : []; $proxies = array_filter(array_map('trim', preg_split('/[\s,]+/', (string) ($input['trusted_proxies'] ?? ''))), [Selfcap_IP::class, 'is_valid_range']); return [ 'enabled' => empty($input['enabled']) ? 0 : 1, 'forms' => array_values(array_intersect(array_keys(Selfcap_Plugin::forms()), (array) ($input['forms'] ?? []))), 'theme' => in_array($input['theme'] ?? '', ['auto', 'light', 'dark'], true) ? $input['theme'] : 'auto', 'language' => isset(Selfcap_Plugin::LANGUAGES[$input['language'] ?? '']) ? $input['language'] : 'auto', 'align' => in_array($input['align'] ?? '', ['left', 'center', 'right'], true) ? $input['align'] : 'left', 'plugin_language' => isset(Selfcap_Plugin::LANGUAGES[$input['plugin_language'] ?? '']) ? $input['plugin_language'] : 'auto', 'difficulty' => max(10, min(24, (int) ($input['difficulty'] ?? 18))), 'auto_block' => empty($input['auto_block']) ? 0 : 1, 'ip_headers' => empty($input['ip_headers']) ? 0 : 1, 'block_xmlrpc' => empty($input['block_xmlrpc']) ? 0 : 1, 'trusted_proxies' => implode("\n", $proxies), 'retention_days' => max(1, min(365, (int) ($input['retention_days'] ?? 30))), 'checkout_position' => array_key_exists((string) ($input['checkout_position'] ?? ''), Selfcap_Plugin::CHECKOUT_HOOKS) ? $input['checkout_position'] : 'button', // A CSS selector, only ever used by querySelector() in the browser. 'checkout_selector' => substr(trim(sanitize_text_field((string) ($input['checkout_selector'] ?? ''))), 0, 200), ]; } private static function url(string $tab, array $args = []): string { return add_query_arg(array_merge(['page' => self::SLUG, 'tab' => $tab], $args), admin_url('admin.php')); } // ---- Rule actions --------------------------------------------------- public static function add_rule(): void { if (! current_user_can('manage_options')) { wp_die(esc_html__('Not allowed.', 'selfcap'), '', ['response' => 403]); } check_admin_referer('selfcap_add_rule'); $range = isset($_POST['ip_range']) ? trim(sanitize_text_field(wp_unslash($_POST['ip_range']))) : ''; $type = isset($_POST['type']) && $_POST['type'] === 'allow' ? 'allow' : 'block'; $reason = isset($_POST['reason']) ? sanitize_text_field(wp_unslash($_POST['reason'])) : ''; $hours = isset($_POST['hours']) ? absint($_POST['hours']) : 0; if (! Selfcap_IP::is_valid_range($range)) { wp_safe_redirect(self::url('rules', ['selfcap_notice' => 'invalid'])); exit; } Selfcap_Store::add_rule($type, $range, $reason, 'manual', $hours > 0 ? time() + $hours * HOUR_IN_SECONDS : null); wp_safe_redirect(self::url('rules', ['selfcap_notice' => 'added'])); exit; } public static function delete_rule(): void { if (! current_user_can('manage_options')) { wp_die(esc_html__('Not allowed.', 'selfcap'), '', ['response' => 403]); } $id = isset($_GET['rule']) ? absint($_GET['rule']) : 0; check_admin_referer('selfcap_delete_rule_'.$id); Selfcap_Store::delete_rule($id); wp_safe_redirect(self::url('rules', ['selfcap_notice' => 'deleted'])); exit; } // ---- Page ----------------------------------------------------------- public static function page(): void { if (! current_user_can('manage_options')) { return; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended $tab = isset($_GET['tab']) ? sanitize_key($_GET['tab']) : 'overview'; $tabs = [ 'overview' => __('Overview', 'selfcap'), 'rules' => __('IP rules', 'selfcap'), 'settings' => __('Settings', 'selfcap'), ]; if (! isset($tabs[$tab])) { $tab = 'overview'; } $enabled = Selfcap_Plugin::is_enabled(); $forms = count(array_intersect(array_keys(Selfcap_Plugin::forms()), (array) Selfcap_Plugin::options()['forms'])); ?>

Selfcap v


get_results($wpdb->prepare('SELECT * FROM %i WHERE day >= %s ORDER BY day', $stats, $since), OBJECT_K); $total = (int) $wpdb->get_var($wpdb->prepare( "SELECT COUNT(*) FROM %i WHERE (%s = '' OR result = %s) AND (%s = '' OR ip = %s)", $log, $result, $result, $ip, $ip )); $rows = (array) $wpdb->get_results($wpdb->prepare( "SELECT * FROM %i WHERE (%s = '' OR result = %s) AND (%s = '' OR ip = %s) ORDER BY id DESC LIMIT %d OFFSET %d", $log, $result, $result, $ip, $ip, $per_page, ($paged - 1) * $per_page )); // phpcs:enable $totals = array_fill_keys(Selfcap_Store::STAT_COLUMNS, 0); $series = []; $peak = 0; for ($offset = $range - 1; $offset >= 0; $offset--) { $time = $now - $offset * DAY_IN_SECONDS; $date = wp_date('Y-m-d', $time); $day = $days[$date] ?? null; $point = ['time' => $time, 'date' => $date, 'offset' => $offset]; foreach (Selfcap_Store::STAT_COLUMNS as $column) { $point[$column] = $day ? (int) $day->$column : 0; $totals[$column] += $point[$column]; } $peak = max($peak, $point['passed'] + $point['failed'] + $point['blocked']); $series[] = $point; } $answered = $totals['passed'] + $totals['failed']; $labels = [ 'passed' => __('Approved', 'selfcap'), 'failed' => __('Refused', 'selfcap'), 'blocked' => __('Blocked', 'selfcap'), ]; ?>

>
0 /* translators: %s: percentage */ ? sprintf(__('%s of the answers', 'selfcap'), self::percent($totals['passed'], $answered)) : __('No answers yet', 'selfcap'), 'passed'); self::stat(__('Refused', 'selfcap'), $totals['failed'], $answered > 0 /* translators: %s: percentage */ ? sprintf(__('%s of the answers', 'selfcap'), self::percent($totals['failed'], $answered)) : __('Bots and failed checks', 'selfcap'), 'failed'); self::stat(__('Blocked', 'selfcap'), $totals['blocked'], __('Stopped by an IP rule', 'selfcap'), 'blocked'); self::stat(__('Challenges issued', 'selfcap'), $totals['challenges'], __('Times the widget was shown', 'selfcap')); self::stat(__('Forms validated', 'selfcap'), $totals['validated'], __('Submissions that got through', 'selfcap')); ?>

result]) ? $row->result : 'blocked'; ?>
created_at, $now))); ?> created_at)); ?> ip); ?> score); ?> reason))) as $reason) : ?> solve_ms === null ? '' : esc_html(number_format_i18n((int) $row->solve_ms).' ms'); ?> user_agent)); ?>
$range, 'result' => $result, 'ip' => $ip]))); ?>
(int) ceil($range / 10), 'is-some' => (int) ceil($range / 6), 'is-few' => (int) ceil($range / 3)]; $first = true; ?>
0) : ?>
add_query_arg('paged', '%#%', add_query_arg('per_page', $per_page, $base)), 'format' => '', 'current' => $paged, 'total' => max(1, (int) ceil($total / $per_page)), 'prev_text' => '‹', 'next_text' => '›', ]); ?>
>
get_col($wpdb->prepare('SELECT ip FROM %i ORDER BY id DESC LIMIT %d', Selfcap_Store::table('log'), 50)); if (count($ips) < 10) { return false; } return count(array_filter($ips, [Selfcap_IP::class, 'is_private'])) * 2 >= count($ips); } /** The page size asked for (and remembered), else the admin's last choice, else 10. */ private static function per_page(int $asked): int { $user = get_current_user_id(); if (in_array($asked, self::PER_PAGE_OPTIONS, true)) { update_user_meta($user, self::PER_PAGE_META, $asked); return $asked; } $saved = (int) get_user_meta($user, self::PER_PAGE_META, true); return in_array($saved, self::PER_PAGE_OPTIONS, true) ? $saved : self::PER_PAGE_DEFAULT; } /** A round number at or above the peak whose half is round too: 4, 10, 20, 50, 100... */ private static function axis_top(int $peak): int { if ($peak <= 4) { return 4; } $magnitude = 10 ** (int) floor(log10($peak)); foreach ([1, 2, 4, 5, 10] as $factor) { if ($factor * $magnitude >= $peak && ($factor * $magnitude) % 2 === 0) { return (int) ($factor * $magnitude); } } return (int) (10 * $magnitude); } private static function percent(int $part, int $whole): string { return number_format_i18n($part / $whole * 100, $part === $whole || $part === 0 ? 0 : 1).'%'; } /** "Chrome on macOS" out of a user agent. The full string stays in the cell's title. */ private static function browser(string $agent): string { if ($agent === '') { return '—'; } $browsers = ['Edg' => 'Edge', 'OPR' => 'Opera', 'SamsungBrowser' => 'Samsung Internet', 'Firefox' => 'Firefox', 'FxiOS' => 'Firefox', 'HeadlessChrome' => 'Headless Chrome', 'CriOS' => 'Chrome', 'Chrome' => 'Chrome', 'Safari' => 'Safari']; $systems = ['Windows' => 'Windows', 'Android' => 'Android', 'iPhone' => 'iOS', 'iPad' => 'iPadOS', 'Mac OS X' => 'macOS', 'CrOS' => 'ChromeOS', 'Linux' => 'Linux']; $browser = ''; $system = ''; foreach ($browsers as $needle => $name) { if (preg_match('/'.preg_quote($needle, '/').'\/(\d+)/', $agent, $match)) { $browser = $name.' '.$match[1]; break; } } foreach ($systems as $needle => $name) { if (strpos($agent, $needle) !== false) { $system = $name; break; } } if ($browser === '') { return strlen($agent) > 40 ? substr($agent, 0, 40).'…' : $agent; } return $system === '' ? $browser : $browser.' · '.$system; } // ---- IP rules ------------------------------------------------------- private static function rules_tab(): void { global $wpdb; $table = Selfcap_Store::table('rules'); $now = time(); // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.Security.NonceVerification.Recommended $paged = max(1, isset($_GET['paged']) ? absint($_GET['paged']) : 1); $per_page = self::per_page(isset($_GET['per_page']) ? absint($_GET['per_page']) : 0); $total = (int) $wpdb->get_var($wpdb->prepare('SELECT COUNT(*) FROM %i', $table)); // Manual rules first: an attack can create thousands of automatic ones. $rules = (array) $wpdb->get_results($wpdb->prepare( "SELECT * FROM %i ORDER BY (source = 'manual') DESC, id DESC LIMIT %d OFFSET %d", $table, $per_page, ($paged - 1) * $per_page )); $notice = isset($_GET['selfcap_notice']) ? sanitize_key($_GET['selfcap_notice']) : ''; $prefill = isset($_GET['prefill']) ? trim(sanitize_text_field(wp_unslash($_GET['prefill']))) : ''; // phpcs:enable $prefill = Selfcap_IP::is_valid_range($prefill) ? $prefill : ''; $notices = [ 'added' => ['success', __('Rule added.', 'selfcap')], 'deleted' => ['success', __('Rule removed.', 'selfcap')], 'invalid' => ['error', __('That is not a valid IP address or CIDR range.', 'selfcap')], ]; if (isset($notices[$notice])) { printf('

%s

', esc_attr($notices[$notice][0]), esc_html($notices[$notice][1])); } ?>

'.esc_html(Selfcap_Plugin::client_ip()).''), ['code' => []]); ?>

expires_at !== null && (int) $rule->expires_at <= $now; $remove = wp_nonce_url(add_query_arg(['action' => 'selfcap_delete_rule', 'rule' => (int) $rule->id], admin_url('admin-post.php')), 'selfcap_delete_rule_'.(int) $rule->id); ?>
type === 'allow' ? __('Allow', 'selfcap') : __('Block', 'selfcap')); ?> ip_range); ?> source === 'auto' ? __('Automatic', 'selfcap') : __('Manual', 'selfcap')); ?> reason); ?> created_at)); ?> expires_at === null) { esc_html_e('Never', 'selfcap'); } elseif ($expired) { esc_html_e('Expired', 'selfcap'); } else { /* translators: %s: time span, like "5 minutes" */ echo esc_html(sprintf(__('In %s', 'selfcap'), human_time_diff($now, (int) $rule->expires_at))); } ?>
$language[0], Selfcap_Plugin::LANGUAGES); settings_errors(); ?>

$label) : ?>

>