compat = $compat ?? new ABDS_SEO_Compat_Detector(); } /** * Registers this class's hooks with the plugin's hook loader. * * @param ABDS_SEO_Loader $loader Hook loader. */ public function register_hooks( ABDS_SEO_Loader $loader ): void { $loader->add_action( 'init', $this, 'add_rewrite_rule' ); $loader->add_filter( 'query_vars', $this, 'add_query_var' ); // Priority 5: WordPress core's own redirect_canonical() also runs on // template_redirect at the default priority (10) and, for a rewrite // endpoint core doesn't itself recognize, adds a trailing slash and // 301s before this handler would ever run — same class of bug as // ABDS_SEO_Frontend_Output::maybe_redirect_attachment(), caught live // here the same way (curl -i showing the unwanted 301). $loader->add_action( 'template_redirect', $this, 'maybe_serve_sitemap', 5 ); $loader->add_filter( 'wp_sitemaps_enabled', $this, 'maybe_disable_core_sitemap' ); $loader->add_filter( 'robots_txt', $this, 'add_sitemap_line', 10, 1 ); foreach ( array( 'save_post', 'deleted_post', 'trashed_post', 'saved_term', 'deleted_term' ) as $hook ) { $loader->add_action( $hook, $this, 'invalidate_cache' ); } $loader->add_action( 'update_option_abds_seo_settings', $this, 'invalidate_cache' ); // permalink_structure_changed fires when an admin re-saves Permalinks // in wp-admin — exactly the action already tried, by hand, on // neborak.com.ua. Forcing a fresh verification right then (instead // of waiting out VERIFIED_TRANSIENT_TTL) means that if whatever's // intercepting /sitemap.xml there ever gets resolved, the very next // permalinks save is enough to bring core's sitemap and the // robots.txt line back in sync with reality, not up to an hour later. $loader->add_action( 'permalink_structure_changed', $this, 'invalidate_verified_cache' ); // 1.6: the deferred, longer-timeout retry after a TIMEOUT-classified // CHECK_FAILED. This plugin's first use of wp-cron. $loader->add_action( self::RETRY_CRON_HOOK, $this, 'run_scheduled_retry' ); } /** * Registers the /sitemap.xml rewrite rule. Existing sites need a * rewrite-rules flush to pick this up — ABDS_SEO_Settings_Installer's * R2 backfill already does this once (see that class's own docblock); * new installs get it free from ABDS_SEO_Activator::activate(). */ public function add_rewrite_rule(): void { add_rewrite_rule( '^sitemap\.xml$', 'index.php?abds_seo_sitemap=1', 'top' ); } /** * Whitelists the sitemap query var so WordPress's rewrite parsing * doesn't strip it. * * @param array $vars Existing public query vars. * @return array */ public function add_query_var( array $vars ): array { $vars[] = 'abds_seo_sitemap'; return $vars; } /** * Disables WordPress core's own /wp-sitemap.xml while this plugin's own * sitemap is ACTUALLY live, so a site never carries two — but never at * the cost of a site having zero sitemaps. * * Confirmed live bug (neborak.com.ua), and worse than first understood: * checking that the rewrite rule merely EXISTS in the rewrite_rules * option (the previous version of this check) is not the same claim as * "a request to /sitemap.xml actually gets XML back" — on that site * something ahead of this plugin (candidates: Polylang, iDance Site * Builder, the theme — under investigation) intercepts /sitemap.xml and * sends it to /wp-sitemap.xml before this plugin's handler ever runs, * while the rule itself stays present in the option the whole time. The * old check would see the key and confidently disable core's sitemap * anyway, leaving the site with neither. Now asks the one question that * actually matters — own_sitemap_is_actually_serving() — a real, * cached loopback request to the plugin's own /sitemap.xml, same * pattern ABDS_SEO_Robots_Txt_Checker already uses for /robots.txt. * Left alone (returns the incoming value untouched) when suppressed by * a competitor — its own sitemap handling should not be second-guessed * here. * * @param bool $enabled Whether wp-sitemap.xml is currently enabled. * @return bool */ public function maybe_disable_core_sitemap( $enabled ) { if ( $this->is_suppressed() || $this->is_probe_request() ) { return $enabled; } return $this->own_sitemap_is_actually_serving() ? false : $enabled; } /** * Whether a request to /sitemap.xml actually gets a real sitemap back * right now — a thin bool view over probe_sitemap_status() for * maybe_disable_core_sitemap() and add_sitemap_line(), which only ever * need to distinguish CONFIRMED from everything else: NOT_CONFIRMED * and CHECK_FAILED behave identically for them (core's sitemap stays * enabled, no Sitemap: line is added, either way) — the distinction * between the two only matters for what the admin is told, in * status() below, never for this toggle. * * @return bool */ protected function own_sitemap_is_actually_serving(): bool { return self::PROBE_STATUS_CONFIRMED === $this->probe_sitemap_status()['status']; } /** * The cached, three-valued probe result: CONFIRMED (a real 200 XML * response), NOT_CONFIRMED (a real response, but not that), or * CHECK_FAILED (the loopback request itself never completed — nothing * is known either way). Cached — a live HTTP round trip on every page * load would be its own regression — with CHECK_FAILED given its own, * much shorter TTL (see CHECK_FAILED_TRANSIENT_TTL's docblock). * * @return array{status:string,error:string} */ protected function probe_sitemap_status(): array { $cached = get_transient( self::VERIFIED_TRANSIENT_KEY ); if ( is_array( $cached ) && isset( $cached['status'] ) ) { return $cached; } $result = $this->run_probe_and_cache( self::PROBE_TIMEOUT_SECONDS ); // Only the routine (short-timeout) path ever schedules a retry — // run_scheduled_retry() and check_again() call run_probe_and_cache() // directly, bypassing this, which is what enforces "one retry", not // "one retry that can itself retry again". $this->maybe_schedule_retry( $result ); return $result; } /** * Runs one probe attempt at the given timeout and caches it with the * status-appropriate TTL. Shared by the routine cache-miss path * (PROBE_TIMEOUT_SECONDS) and both deliberate-retry callers, * run_scheduled_retry() and check_again() (PROBE_RETRY_TIMEOUT_SECONDS) * — see that constant's own docblock for why those two contexts are * allowed to use the longer value and nothing else is. * * @param int $timeout Seconds. * @return array{status:string,error:string,error_type:string} */ protected function run_probe_and_cache( int $timeout ): array { $result = $this->probe_sitemap_response( $timeout ); $ttl = self::PROBE_STATUS_CHECK_FAILED === $result['status'] ? self::CHECK_FAILED_TRANSIENT_TTL : self::VERIFIED_TRANSIENT_TTL; set_transient( self::VERIFIED_TRANSIENT_KEY, $result, $ttl ); return $result; } /** * Schedules run_scheduled_retry() a bit later, but only when the * just-computed result is TIMEOUT-classified — never for * CONNECTION-classified failures. A timeout and a connection refusal * are different claims about the environment: a timeout says "the * request didn't get an answer in time", which a slower or * momentarily loaded host can produce on an otherwise-working setup, * and simply waiting a bit longer with more room has a real chance of * getting a real answer. A connection refusal, a DNS failure, or a * blocked loopback says the request couldn't even be attempted — * conditions a longer timeout cannot fix, since the failure was never * about time in the first place. Retrying those would just spend an * extra outbound request for the same, predictable outcome. * * The wp_next_scheduled() check guards against stacking duplicate * events if this fires more than once inside the CHECK_FAILED TTL * window (e.g. two concurrent cache-miss requests racing) — this, * together with probe_sitemap_status() being the only caller, is what * enforces "one retry", not "one retry per request that happens to * see a cache miss". * * @param array{status:string,error:string,error_type:string} $result The freshly computed (not cached) probe result. */ protected function maybe_schedule_retry( array $result ): void { if ( self::PROBE_STATUS_CHECK_FAILED !== $result['status'] ) { return; } if ( self::PROBE_ERROR_TYPE_TIMEOUT !== $result['error_type'] ) { return; } if ( wp_next_scheduled( self::RETRY_CRON_HOOK ) ) { return; } wp_schedule_single_event( time() + self::RETRY_DELAY_SECONDS, self::RETRY_CRON_HOOK ); } /** * The cron callback: the ONE deferred, longer-timeout retry after a * TIMEOUT (see RETRY_DELAY_SECONDS / PROBE_RETRY_TIMEOUT_SECONDS). * Never runs synchronously on a request an admin or visitor is * waiting on — wp-cron's own pseudo-cron dispatch runs it on whatever * unrelated request happens to trigger it, well after that request's * own response has nothing left depending on this method's result. * * Guards against clobbering a fresher, already-resolved result: if * the cache has since moved on (the natural TTL already re-probed, an * admin already clicked "Check again", or the underlying cause * changed), this is a stale scheduled event for a problem that no * longer needs retrying, and does nothing. */ public function run_scheduled_retry(): void { $cached = get_transient( self::VERIFIED_TRANSIENT_KEY ); if ( is_array( $cached ) && isset( $cached['status'] ) ) { $still_pending = self::PROBE_STATUS_CHECK_FAILED === $cached['status'] && self::PROBE_ERROR_TYPE_TIMEOUT === ( $cached['error_type'] ?? '' ); if ( ! $still_pending ) { return; } } $this->run_probe_and_cache( self::PROBE_RETRY_TIMEOUT_SECONDS ); } /** * "Check again" — the explicit, user-initiated re-probe (REST: POST * /sitemap/check-again). The other of the two contexts allowed to use * PROBE_RETRY_TIMEOUT_SECONDS synchronously: the admin clicked a * button and is actively waiting for THIS answer, unlike a passive * page load or a background cron tick. Always runs a fresh probe * (ignores and overwrites any cache) regardless of the current cached * status or error_type — a manual recheck is a general "try again * right now" action, not conditioned on the specific failure * sub-type the way the automatic cron retry is. * * @return array{status:string,error:string,error_type:string} */ public function check_again(): array { return $this->run_probe_and_cache( self::PROBE_RETRY_TIMEOUT_SECONDS ); } /** * The actual loopback request: fetches the site's own /sitemap.xml and * classifies the outcome into one of the three PROBE_STATUS_* values. * A 200 with an HTML body (an interceptor's redirect target, a theme * 404 page that returns 200, a caching layer's error page) is * NOT_CONFIRMED, same as any other wrong response — the point of this * check is to catch exactly that kind of false positive, not just any * 200. A WP_Error (connection refused, timeout, loopback blocked by * the host) is CHECK_FAILED, never NOT_CONFIRMED — the plugin has no * basis to claim the sitemap doesn't work when the honest answer is * that it couldn't ask. * * Deliberate scope boundary, not an oversight: this catches bug class * #1 -- something ahead of the plugin intercepts the request entirely, * so the response is wrong at the transport level (wrong code, wrong * content-type, an HTML body). It does NOT and cannot catch bug class * #2 -- a response that is genuinely 200 and genuinely valid XML, but * incomplete (e.g. missing a language's URLs under Polylang, see the * planned 0.13.0 language-aware generator). Nothing here should be * read as covering that second class; it needs the sitemap's actual * contents inspected, which this transport-level check never does. * * Stamped with PROBE_QUERY_ARG so the request this triggers can * recognize itself via is_probe_request() and skip re-verifying — * without that, wp_sitemaps_enabled firing on the loopback request's * own init hook would recurse into another loopback request, * indefinitely. * * @param int $timeout Seconds — PROBE_TIMEOUT_SECONDS for the routine * path, PROBE_RETRY_TIMEOUT_SECONDS for the two * deliberate-retry callers (see run_probe_and_cache()). * @return array{status:string,error:string,error_type:string} */ protected function probe_sitemap_response( int $timeout ): array { $url = add_query_arg( self::PROBE_QUERY_ARG, '1', home_url( '/sitemap.xml' ) ); $response = wp_remote_get( $url, array( 'timeout' => $timeout ) ); if ( is_wp_error( $response ) ) { return array( 'status' => self::PROBE_STATUS_CHECK_FAILED, 'error' => $response->get_error_message(), 'error_type' => $this->classify_probe_error( $response ), ); } if ( 200 !== (int) wp_remote_retrieve_response_code( $response ) ) { return array( 'status' => self::PROBE_STATUS_NOT_CONFIRMED, 'error' => '', 'error_type' => '', ); } $content_type = (string) wp_remote_retrieve_header( $response, 'content-type' ); if ( false === stripos( $content_type, 'xml' ) ) { return array( 'status' => self::PROBE_STATUS_NOT_CONFIRMED, 'error' => '', 'error_type' => '', ); } $body = ltrim( (string) wp_remote_retrieve_body( $response ) ); $is_xml = 0 === stripos( $body, ' $is_xml ? self::PROBE_STATUS_CONFIRMED : self::PROBE_STATUS_NOT_CONFIRMED, 'error' => '', 'error_type' => '', ); } /** * Classifies a failed probe's WP_Error into TIMEOUT or CONNECTION. * WP_Http (both the cURL and streams transports it can use, * depending on the host) doesn't expose a structured error code for * this distinction — only free-text messages that differ by * transport and PHP build. Pattern-matches on "time" (covers "timed * out" / "Operation timed out", present in both cURL error 28's own * wording and the streams transport's), which is the one substring * reliably present across both transports' timeout messages and * absent from their refusal/DNS/blocked-loopback messages * ("Connection refused", "Failed to connect() to host", "Could not * resolve host"). Anything that doesn't match is classified * CONNECTION — a deliberately broad bucket covering every other * failure mode, since only the TIMEOUT/not-TIMEOUT distinction is * actually acted on (see maybe_schedule_retry()). * * @param WP_Error $error The failed probe's error. * @return string self::PROBE_ERROR_TYPE_TIMEOUT or self::PROBE_ERROR_TYPE_CONNECTION. */ protected function classify_probe_error( WP_Error $error ): string { $message = strtolower( $error->get_error_message() ); return ( false !== strpos( $message, 'time' ) ) ? self::PROBE_ERROR_TYPE_TIMEOUT : self::PROBE_ERROR_TYPE_CONNECTION; } /** * Whether the current request is the plugin's own loopback verification * probe, not a real visitor or crawler request — see * probe_sitemap_response()'s docblock for why this guard exists. * * @return bool */ protected function is_probe_request(): bool { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only recursion guard on the plugin's own outbound loopback request, not user input driving any state change. return isset( $_GET[ self::PROBE_QUERY_ARG ] ); } /** * Adds a Sitemap: line to the virtual robots.txt so search engines can * discover /sitemap.xml without waiting to find a link to it — confirmed * missing entirely (neborak.com.ua had no Sitemap: line at all, for the * unrelated reason that the plugin's sitemap was never live there to * begin with). Only when the plugin's own sitemap is actually live, * same ground-truth check as maybe_disable_core_sitemap() — never * advertises a URL that would 404 or silently redirect elsewhere. * * @param string $output Existing robots.txt content. * @return string */ public function add_sitemap_line( $output ) { if ( $this->is_suppressed() || $this->is_probe_request() || ! $this->own_sitemap_is_actually_serving() ) { return $output; } return rtrim( (string) $output ) . "\nSitemap: " . home_url( '/sitemap.xml' ) . "\n"; } /** * Serves the cached sitemap XML when the rewrite rule matched. 404s * (via WordPress's own not-found handling) when suppressed, so a * competitor's real sitemap — if it also claims /sitemap.xml — isn't * shadowed by an empty response from this plugin. */ public function maybe_serve_sitemap(): void { if ( '1' !== get_query_var( 'abds_seo_sitemap' ) ) { return; } if ( $this->is_suppressed() ) { global $wp_query; $wp_query->set_404(); status_header( 404 ); return; } header( 'Content-Type: application/xml; charset=UTF-8' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- get_cached_xml()/ABDS_SEO_Sitemap_Generator already escape every dynamic value (esc_url()/esc_html()) while assembling the XML string itself. echo $this->get_cached_xml(); exit; } /** * Returns the cached sitemap XML, regenerating (and re-caching) it * first if there's no valid cache. * * @return string */ public function get_cached_xml(): string { $cached = get_transient( self::TRANSIENT_KEY ); if ( is_string( $cached ) ) { return $cached; } return $this->regenerate(); } /** * Forces a fresh build, re-caches it, and records when it happened — * used by both a stale-cache read and the REST "regenerate" action. * * @return string */ public function regenerate(): string { $built = ABDS_SEO_Sitemap_Generator::build(); $xml = $built['xml']; set_transient( self::TRANSIENT_KEY, $xml, self::TRANSIENT_TTL ); update_option( self::LAST_GENERATED_OPTION, time() ); update_option( self::POST_URLS_OPTION, $built['post_urls'], false ); return $xml; } /** * Drops the cached sitemap so the next request rebuilds it. Hooked to * every content change that could affect sitemap membership. */ public function invalidate_cache(): void { delete_transient( self::TRANSIENT_KEY ); } /** * Drops the cached loopback-verification result so the next check * re-probes /sitemap.xml for real, instead of trusting a result that * may predate whatever changed. Kept separate from invalidate_cache(): * that one reacts to content changes (the sitemap's own membership), * this one reacts to routing changes (whether the URL resolves at all). */ public function invalidate_verified_cache(): void { delete_transient( self::VERIFIED_TRANSIENT_KEY ); } /** * A status snapshot for the Indexing screen's Sitemap tab: whether * output is currently suppressed, the real probe outcome, how many * URLs the cached (or freshly built) sitemap holds, and when it was * last generated. * * `status` used to be a hardcoded 'active' whenever not suppressed — * never actually consulting the probe, so the admin screen could say * "active" while core's sitemap was silently the one really serving. * Now returns the real three-valued outcome so that state is visible * instead of hidden: 'confirmed' (own sitemap verified live), * 'not_confirmed' (probed, and it isn't — core's sitemap is the one * actually in effect), or 'check_failed' (the probe itself couldn't * complete — genuinely unknown, see probe_error for why). Wording for * the last two is the caller's job (the REST/JS layer); this method * only ever states the fact the probe returned, never "the sitemap is * broken" — that's not a fact this check has. * * `probe_error_type` (1.6) is '', self::PROBE_ERROR_TYPE_TIMEOUT, or * self::PROBE_ERROR_TYPE_CONNECTION — only meaningful alongside * status === 'check_failed'. Not currently used to change what the * Indexing screen shows (the "Check again" action is offered for * either sub-cause alike, see ABDS_SEO_Sitemap_Controller::check_again()'s * own docblock) but exposed so the real, split cause is visible in the * API rather than only inferable from probe_error's free text. * * `coverage` is null unless published posts outnumber the post URLs in the * sitemap (see ABDS_SEO_Sitemap_Coverage for what that does and does not * mean), in which case it is { published, in_sitemap, missing }. * * @return array{status:string,probe_error:string,probe_error_type:string,url_count:int,last_generated:int,sitemap_url:string,coverage:?array} */ public function status(): array { if ( $this->is_suppressed() ) { return array( 'status' => 'suppressed', 'probe_error' => '', 'probe_error_type' => '', 'url_count' => 0, 'last_generated' => 0, 'sitemap_url' => home_url( '/sitemap.xml' ), 'coverage' => null, ); } $probe = $this->probe_sitemap_status(); $xml = $this->get_cached_xml(); // A cache built before the count was recorded has no number to // compare: say nothing rather than guess. $post_urls = get_option( self::POST_URLS_OPTION, null ); $coverage = null === $post_urls || false === $post_urls ? null : ABDS_SEO_Sitemap_Coverage::gap( ABDS_SEO_Sitemap_Coverage::published_count(), (int) $post_urls ); return array( 'status' => $probe['status'], 'probe_error' => $probe['error'], 'probe_error_type' => $probe['error_type'] ?? '', 'url_count' => substr_count( $xml, '' ), 'last_generated' => (int) get_option( self::LAST_GENERATED_OPTION, 0 ), 'sitemap_url' => home_url( '/sitemap.xml' ), 'coverage' => $coverage, ); } /** * Whether sitemap output must be suppressed: a competitor SEO plugin * is active. * * @return bool */ protected function is_suppressed(): bool { return $this->compat->has_active_competitor(); } }