enabled( 'block_agents' ) && ! self::is_protected( $ua_lc ) ) { // 1. The owner's explicit denylist. Each entry is a substring by default, // a glob when it has * / ?, or a regex when wrapped in /…/ — see ua_matches(). foreach ( (array) $settings->get( 'blocked_agents', array() ) as $needle ) { if ( self::ua_matches( $ua_lc, $needle ) ) { $deny = true; break; } } // 2. The spoofed/legacy-device heuristic — the SAME definition the // activity log labels "Likely spoof/scanner", so blocking and reporting // can never drift apart. if ( ! $deny && $settings->enabled( 'block_spoofed' ) && Classifier::is_spoof( $ua_lc ) ) { $deny = true; } } /** * Final say on whether to deny this request. Lets an add-on layer its own * policy on top — an IP allow-list exception that rescues a flagged UA, or * an extra rule that denies one the built-ins passed. Runs AFTER the * protected allow-list, so an add-on can deliberately deny a protected * agent if it really means to (intent overrides the accident-guard). * * @param bool $deny Whether to deny, per the built-in rules. * @param string $ua Lowercased User-Agent ('' when absent). */ return (bool) apply_filters( 'agentimus_deny_request', $deny, $ua_lc ); } /** * Whether a lowercased UA matches a single denylist entry. The entry is read as: * • REGEX when wrapped in /…/ — e.g. `/semrushbot\/\d+/` (forced case-insensitive); * • GLOB when it contains `*` or `?` — `*` = any run, `?` = any one char; * • plain case-insensitive SUBSTRING otherwise (the safe default). * Two accident-guards: an entry that is ONLY wildcards ("*") matches nothing * (blocking everyone is never a sane denylist row, so we treat it as a no-op), * and a regex that fails to compile degrades to a literal substring test so a * typo can never error the endpoint. * * @param string $ua Lowercased, length-bounded User-Agent. * @param string $needle Raw denylist entry. * @return bool */ private static function ua_matches( $ua, $needle ) { $needle = trim( (string) $needle ); if ( '' === $needle ) { return false; } // Explicit /regex/ — only when it actually has an opening and a later closing // slash; otherwise it's just a path-y substring and stays literal. if ( '/' === $needle[0] && false !== strpos( $needle, '/', 1 ) ) { $regex = self::compile_regex( $needle ); if ( null !== $regex ) { return 1 === @preg_match( $regex, $ua ); // phpcs:ignore WordPress.PHP.NoSilencedErrors -- pathological admin pattern must not warn on a public request. } // Unparseable — fall through and match the raw text literally. } // Glob — translate * and ? after escaping everything else, so no other // metacharacter in the admin's text can do anything unexpected. if ( false !== strpos( $needle, '*' ) || false !== strpos( $needle, '?' ) ) { if ( '' === trim( str_replace( array( '*', '?' ), '', $needle ) ) ) { return false; // All-wildcard entry → would block everyone → no-op. } $regex = '#' . str_replace( array( '\*', '\?' ), array( '.*', '.' ), preg_quote( strtolower( $needle ), '#' ) ) . '#'; return 1 === @preg_match( $regex, $ua ); // phpcs:ignore WordPress.PHP.NoSilencedErrors -- defensive; glob output is always valid. } // Default: plain case-insensitive substring. return false !== strpos( $ua, strtolower( $needle ) ); } /** * Turn a `/pattern/` entry into a usable, case-insensitive PCRE, or null if it * doesn't compile. Re-delimited to `#` (so the user's `/` need not be escaped) * and test-compiled against the empty string before use. * * @param string $needle e.g. "/semrushbot\/\d+/". * @return string|null */ private static function compile_regex( $needle ) { $close = strrpos( $needle, '/' ); $body = (string) substr( $needle, 1, $close - 1 ); if ( '' === $body ) { return null; } $regex = '#' . str_replace( '#', '\#', $body ) . '#i'; return false === @preg_match( $regex, '' ) ? null : $regex; // phpcs:ignore WordPress.PHP.NoSilencedErrors -- compile-probe; invalid pattern returns false. } /** * Whether the UA belongs to a protected agent that must never be denied — the * accident-guard against an over-broad rule. Defaults to the major search * engines (blocking those carries real, silent SEO cost). Filterable: empty it * to allow blocking anything, or extend it with your own always-allow agents. * * @param string $ua_lc Lowercased User-Agent. * @return bool */ private static function is_protected( $ua_lc ) { foreach ( self::protected_agents() as $allow ) { if ( '' !== $allow && false !== strpos( $ua_lc, $allow ) ) { return true; } } return false; } /** * The always-allow agent substrings (lowercase). The default protects the * search engines whose accidental blocking would hurt the site most. * * @return string[] */ public static function protected_agents() { $protected = array( 'googlebot', 'bingbot', 'duckduckbot', 'applebot', 'yandex' ); // The owner's own trust-list (added via the activity panel's "Allow"): these // are never blocked AND never flagged for review, exactly like the engines above. $allowed = (array) ( new Settings() )->get( 'allowed_agents', array() ); $protected = array_merge( $protected, $allowed ); /** * Filter the always-allow list — agents that the block feature must never * deny, whatever the denylist or spoof heuristic say. * * @param string[] $protected Lowercase UA substrings. */ $protected = (array) apply_filters( 'agentimus_block_allowlist', $protected ); return array_values( array_filter( array_map( 'strtolower', array_map( 'trim', $protected ) ) ) ); } /** * Whether a RAW User-Agent belongs to a protected/allow-listed agent (the * search engines that are never denied). Public companion to the internal * lowercase test, so other modules — e.g. the activity panel's threat view — * can treat exactly the same agents as trusted (one definition, no drift). * * @param string $ua Raw User-Agent. * @return bool */ public static function is_protected_ua( $ua ) { return self::is_protected( substr( strtolower( trim( (string) $ua ) ), 0, 1000 ) ); } /** * Derive a SAFE denylist token from a raw User-Agent — the substring the * activity panel's one-click "Block" appends to blocked_agents. Returns '' when * no specific, safe token can be found, so the caller never adds an over-broad * rule. Guarantees: * • a protected search engine yields '' (never proposes blocking Googlebot); * • a generic browser yields '' (its only tokens are mozilla/webkit/chrome/… — * blocking those would 403 every real visitor and most bots); * • a spoofed/legacy-device UA yields '' (handled by the block_spoofed class, * not a token — its tokens are generic too). * What it DOES return is the crawler/tool product token: the `name` in the * standard `name/version` signature (SemrushBot, AhrefsBot, python-requests, …), * skipping generic ones, so blocking is specific to the abusing client. * * @param string $ua Raw User-Agent. * @return string Lowercased token, or '' when none is safe. */ public static function suggest_token( $ua ) { $ua_lc = substr( strtolower( trim( (string) $ua ) ), 0, 1000 ); if ( '' === $ua_lc || self::is_protected( $ua_lc ) ) { return ''; } // A generic HTTP client / scripting tool (curl, wget, python-requests…) has a // broad name, and fetching the AI files is exactly what this plugin invites — // so it is never a safe one-click block. (A heavy one still surfaces for review; // block it explicitly in Settings if you must.) if ( 'Script/tool' === Classifier::classify( $ua_lc ) ) { return ''; } // Every `name/version` pair in the UA, in order. The first one that isn't a // generic engine/browser token is the client's real product name. if ( preg_match_all( '#([a-z][a-z0-9._+-]{1,40})/[0-9]#', $ua_lc, $matches ) ) { foreach ( $matches[1] as $candidate ) { if ( ! self::is_generic_token( $candidate ) ) { return $candidate; } } } // Fallback: a "compatible; Name" comment with no version (some crawlers). if ( preg_match( '#compatible;\s*([a-z][a-z0-9._+-]{1,40})#', $ua_lc, $m ) && ! self::is_generic_token( $m[1] ) ) { return $m[1]; } return ''; } /** * Whether a product token is a generic browser/engine name that must never be a * block rule on its own (it would match nearly every visitor). Filterable. * * @param string $token Lowercased candidate token. * @return bool */ private static function is_generic_token( $token ) { $generic = array( 'mozilla', 'applewebkit', 'gecko', 'khtml', 'webkit', 'like', 'safari', 'chrome', 'chromium', 'crios', 'firefox', 'fxios', 'version', 'edg', 'edge', 'opr', 'opera', 'trident', 'msie', 'mobile', 'windows', 'macintosh', 'linux', 'android', 'ios', 'x11', ); /** * Filter the generic-token stoplist used by the one-click block suggestion. * * @param string[] $generic Lowercase tokens that are never a safe block rule. */ $generic = (array) apply_filters( 'agentimus_generic_ua_tokens', $generic ); return in_array( $token, $generic, true ); } /** * Refuse the current request with a bare 403 and stop — but only when * {@see denies()} says so. A no-op otherwise, so a serve path can gate every * emit with a single leading call. Mirrors the HEAD handling of the real * emitters (headers, no body). */ public static function maybe_block() { if ( ! self::denies() ) { return; } if ( ! headers_sent() ) { status_header( 403 ); nocache_headers(); header( 'Content-Type: text/plain; charset=UTF-8' ); header( 'X-Content-Type-Options: nosniff' ); } $is_head = isset( $_SERVER['REQUEST_METHOD'] ) && 'HEAD' === strtoupper( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) ); if ( ! $is_head ) { echo "403 Forbidden\n"; // phpcs:ignore WordPress.Security.EscapeOutput -- static plain text. } exit; } }