20, 'redirection' => 0, 'headers' => array( 'Authorization' => 'Bearer ' . $token ), ) ); if ( is_wp_error( $response ) ) { return $response; } $code = wp_remote_retrieve_response_code( $response ); if ( 200 !== $code ) { return new WP_Error( 'equalsites_http', sprintf( 'API returned HTTP %d', $code ) ); } $body = json_decode( wp_remote_retrieve_body( $response ), true ); $rules = isset( $body['rules'] ) && is_array( $body['rules'] ) ? $body['rules'] : null; if ( null === $rules ) { return new WP_Error( 'equalsites_body', __( 'Unexpected API response.', 'ableguard-accessibility-toolkit' ) ); } // Unconditional — including when $rules just landed empty — and // deliberately NOT subject to the backoff in `maybe_resync_statement()`. // That gate exists solely to stop the [ableguard_statement] shortcode // turning visitor page views into resync attempts against a failing API; // it has nothing to do with this call, which is only reached twice a day // (cron), once per admin click ("Sync now"), or from the shortcode through // `maybe_sync_rules()`, which applies the same backoff before it gets // here. A rule count dropping to zero is exactly when a fresh, honest // statement matters most, so it gets its attempt right here, in the same // pass, rather than waiting on the next scheduled sync. update_option( 'ableguard_statement_last_attempt', $now, false ); $statement = self::fetch_statement( $api_url, $site_id, $token ); $committed = EqualSites_Connect_Store::commit_sync( $ctx, $rules, $statement, $now ); if ( 'ok' !== $committed ) { return self::skipped( $committed ); } self::write_back_media_alt( $rules, $ctx ); self::report_environment( $api_url, $site_id, $token ); return count( $rules ); } /** * Why a sync, or part of one, wrote nothing. The wording of the first is the notice the * connect flow gives for a held lock (spec 2), so the screen says one thing in both places. */ private static function skipped( $status ) { if ( 'busy' === $status ) { return new WP_Error( 'ableguard_busy', __( 'Another AbleGuard change is in progress on this site. Try again in a moment.', 'ableguard-accessibility-toolkit' ) ); } if ( 'superseded' === $status ) { return new WP_Error( 'ableguard_superseded', __( "The site's AbleGuard connection changed while this sync was running, so its results were not saved. Press Sync now to try again.", 'ableguard-accessibility-toolkit' ) ); } return new WP_Error( 'ableguard_retry', __( 'AbleGuard could not update its stored data on this request. Try again in a moment.', 'ableguard-accessibility-toolkit' ) ); } /** * Approved AI alt text is written into the media library itself — the * permanent fix. It survives plugin deactivation, applies wherever * WordPress renders the attachment (galleries, blocks, featured images), * and is what competitors mean by "alt text generation". The render-time * rule still covers legacy tags hard-coded in old post content. * * Never overwrites: only fills attachments whose alt is currently empty. * * Skipped while the owner has unticked "Apply approved fixes to my pages". * Saved alt text reaches visitors wherever WordPress renders the attachment, so * it is a fix like any other, and the plugin's one pause switch has to stop it * as well as the rewriting of the markup. It used to run on every sync whatever * the setting said, so a paused site went on having alt text saved into its * media library while the settings screen and its published statement said its * pages were not being fixed. What is already saved stays: by then it is part of * the media library, and nothing here takes it back. */ private static function write_back_media_alt( $rules, $ctx ) { if ( ! equalsites_fixes_enabled() ) { return; } $written = 0; foreach ( $rules as $rule ) { if ( empty( $rule['meta']['imageUrl'] ) || empty( $rule['action']['name'] ) || 'alt' !== $rule['action']['name'] || ! empty( $rule['meta']['isDecorative'] ) || '' === trim( (string) ( $rule['action']['value'] ?? '' ) ) ) { continue; } $attachment_id = attachment_url_to_postid( $rule['meta']['imageUrl'] ); if ( ! $attachment_id ) { continue; } $current = get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ); if ( '' !== trim( (string) $current ) ) { continue; } // This runs after the lock is released, and it can take a while on a big library. // So before each attachment it asks again, directly: stop once the connection is // gone or is another one, or once the owner has paused fixes meanwhile. if ( ! EqualSites_Connect_Store::connection_still( $ctx ) || ! equalsites_fixes_enabled() ) { break; } update_post_meta( $attachment_id, '_wp_attachment_image_alt', sanitize_text_field( $rule['action']['value'] ) ); $written++; } if ( $written > 0 ) { update_option( 'ableguard_alt_written', (int) ableguard_option( 'ableguard_alt_written', 'equalsites_alt_written', 0 ) + $written, false ); } } /** * Fetches the generated accessibility statement (HTML fragment) so the * [ableguard_statement] shortcode can render it inside the site's theme. * A missing/failed statement is non-fatal — the last synced copy stays, * subject to the staleness rule in `statement_claim_is_stale()`. * * `ableguard_statement_last_attempt` is recorded whether the fetch * succeeds or fails, by the caller, before the request goes out — it is * what `maybe_resync_statement()` reads to keep the shortcode from * re-attempting on every render. The delivery record's `statement_synced_at` * only moves on success, and is what lets a zero-rules site tell whether * its cached fragment predates the drop to zero (still claiming * remediation that no longer exists) or was written after (already * honest, whatever it says — see statement.ts's renderStatementFragment, * which recomputes from the live rule count and cannot render a false * claim; it can only fail to run). * * @return string|null The fragment, or null when there is none to store. */ private static function fetch_statement( $api_url, $site_id, $token ) { $response = wp_safe_remote_get( $api_url . '/api/sites/' . rawurlencode( $site_id ) . '/statement.html?fragment=1', array( 'timeout' => 20, 'redirection' => 0, 'headers' => array( 'Authorization' => 'Bearer ' . $token ), ) ); if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) { return null; } $html = wp_remote_retrieve_body( $response ); return '' !== $html ? $html : null; } /** * When the site first had zero approved rules, so a cached statement * fragment written while rules were nonzero can eventually be * recognised as a stale claim rather than served forever. Cleared the * moment rules are nonzero again — a healthy site's cache is meant to * survive an unreachable API indefinitely (ADR-010's delivery note), no * matter how long ago it was last confirmed fresh; only a zero-rules site * is a legal-claim risk, and only for as long as it stays at zero. * * Deliberately keeps the *earliest* timestamp, not the latest: while rules * stay at zero, further calls (a later cron sync) must not push it forward, * or the grace period in `statement_claim_is_stale()` would never elapse — * every sync would look like the transition just happened. * * A pure function over the values being committed. It used to read and write * an option, and the shortcode called it on every render; page views write * nothing now, so only a sync and the migration (which starts the grace * period at upgrade time for a site already at zero rules, as the shortcode * did) decide it. * * @param array $rules The approved rules being committed. * @param int $previous The value the same site's delivery record held, or 0. * @param int $now * @return int The value to store: 0 while rules are nonzero. */ public static function zero_rules_since_for( $rules, $previous, $now ) { if ( ! empty( $rules ) ) { return 0; } return $previous ? (int) $previous : (int) $now; } /** * The [ableguard_statement] shortcode's way of getting a statement onto a * site that has none stored: a full sync, run while the visitor's page is * being built. * * That is three outbound requests, each allowed to wait 15 to 20 seconds, and * the next visitor's page view will find exactly what this one did — a site * with no statement is one that has not been scanned yet, or whose API is * down. Run on every view it turned traffic on the statement page into * traffic on the AbleGuard API, and into a long wait for each visitor while * that API was slow. * * So it shares the window of `maybe_resync_statement()`: one attempt per * STATEMENT_RETRY_BACKOFF for the whole site, whoever the visitor is. The * attempt is recorded before the requests go out, not after they return. A * window that only closes once the first sync has finished stays open for as * long as a slow API takes to answer, and every visitor who arrives in that * time starts a sync of their own. * * Nothing is recorded while the connection details are not saved: no request * would be made, and an attempt on record would hold off the first real sync * after the owner connects the site. * * @param int|null $now Injectable for tests; production callers always omit it. * @return bool Whether a sync was actually started. */ public static function maybe_sync_rules( $now = null ) { $now = null === $now ? time() : $now; if ( ! self::connection_details_saved() || ! self::retry_window_is_open( $now ) ) { return false; } update_option( 'ableguard_statement_last_attempt', $now, false ); self::sync_rules( $now ); return true; } /** * The [ableguard_statement] shortcode's own chance to refresh a stale * statement, rate-limited so that traffic on the page carrying the * shortcode cannot turn a failing statement endpoint into a resync * attempt on every visitor request. The twice-daily cron and an admin's * manual "Sync now" both call `sync_rules()` directly and skip this * gate entirely — they are already rate-limited by their own trigger, not * by page traffic. * * @param int|null $now Injectable for tests; production callers always omit it. * @return bool Whether an attempt was actually made. */ public static function maybe_resync_statement( $now = null ) { $now = null === $now ? time() : $now; if ( ! self::retry_window_is_open( $now ) ) { return false; } // The same first step as a sync: under the lock, migrate if need be, read the // connection directly, release. A busy lock is not an attempt, so it records none. $ctx = EqualSites_Connect_Store::begin_sync(); if ( 'ok' !== $ctx['status'] ) { return false; } $api_url = ableguard_api_origin( $ctx['api_url'] ); if ( '' === $api_url || ! $ctx['active'] ) { return false; } update_option( 'ableguard_statement_last_attempt', $now, false ); $html = self::fetch_statement( $api_url, $ctx['site_id'], $ctx['token'] ); if ( null !== $html ) { EqualSites_Connect_Store::commit_statement( $ctx, $html, $now ); } return true; } /** * Whether it is at least STATEMENT_RETRY_BACKOFF seconds since the last * recorded statement attempt. `maybe_sync_rules()` and `sync_rules()` are * what record one, so a sync from the cron or a "Sync now" press holds the * shortcode back as well. Read directly: it is a clock a page view's decision * hangs on, and a stale cached value would let every visitor through. */ private static function retry_window_is_open( $now ) { return $now - EqualSites_Connect_Store::statement_last_attempt() >= self::STATEMENT_RETRY_BACKOFF; } /** The values `sync_rules()` refuses to run without, read directly. */ private static function connection_details_saved() { $connection = EqualSites_Connect_Store::connection_direct(); return '' !== ableguard_api_origin( $connection['api_url'] ) && $connection['has_connection']; } /** * Whether the [ableguard_statement] shortcode must refuse to render its * cached fragment even though one exists. The state machine in full: * * 1. FRESH. Rules nonzero — or rules zero but the cached fragment was * written at or after the moment rules last read zero, so it was * generated already knowing that (renderStatementFragment recomputes * from the live count and cannot render a false claim; it can only * fail to run). Render the cache. This is also where a healthy, * nonzero-rules site sits indefinitely while the API is unreachable — * ADR-010's designed "stays up even if the API is unreachable" * behavior — and it must survive no matter how old the last * successful sync is. * 2. ZERO, STALE, WITHIN GRACE. Rules zero, the cached fragment predates * that transition (written while rules were nonzero, still claiming * active remediation), but fewer than STATEMENT_STALE_GRACE seconds * have passed since rules first read zero. Render the cache anyway — * a bulk rejection reversed a minute later, or an API hiccup at the * exact moment entitlement lapsed, should not instantly blank a * customer's published legal page. * 3. ZERO, STALE, EXHAUSTED. Same as 2, but the grace period has elapsed * with no fresher statement landed. Refuse to render — a false * compliance claim left up indefinitely is exactly what ADR-010 * exists to prevent, and "the API happens to be down" stops being a * technical detail and becomes the visitor-facing outcome. * * @param array $delivery The delivery being judged: `rules`, `zero_rules_since` and * `statement_synced_at`, as the page snapshot or the delivery * record carries them. Both fields are read from the same row as * the statement they judge. * @param int|null $now Injectable for tests; production callers always omit it. */ public static function statement_claim_is_stale( $delivery, $now = null ) { $rules = isset( $delivery['rules'] ) ? $delivery['rules'] : array(); if ( ! empty( $rules ) ) { return false; } $zero_since = (int) ( isset( $delivery['zero_rules_since'] ) ? $delivery['zero_rules_since'] : 0 ); if ( 0 === $zero_since ) { return false; } $synced_at = (int) ( isset( $delivery['statement_synced_at'] ) ? $delivery['statement_synced_at'] : 0 ); if ( $synced_at >= $zero_since ) { return false; } $now = null === $now ? time() : $now; return ( $now - $zero_since ) > self::STATEMENT_STALE_GRACE; } /** * What this connector reports about itself. * * Two jobs, and they used to be one. The theme, locale, plugin list and versions * power issue→source attribution. `enabled` is the connector's own state, and it * is the field the SaaS needs to say anything true about fixes reaching visitors: * this plugin only applies them when the owner's "Apply approved fixes" box is * ticked (`equalsites_fixes_enabled`, read by the output buffer in * ableguard.php), and until now the report said nothing about it. * * What that cost: unticking the box stops every fix at the buffer, but the sync * schedule is registered at activation and cleared at deactivation, not by this * setting — so a paused site went on reporting in twice a day, its report went on * looking exactly like a working site's, and its published accessibility * statement went on claiming that AbleGuard corrects the HTML before each page is * sent, including for visitors whose browser runs no JavaScript. A false * compliance claim, made because of a decision the owner had taken deliberately * and told us about in the only place they could. * * The sync deliberately keeps running while fixes are paused. Going quiet would * make the SaaS lose sight of the site altogether, which reads as "we cannot tell" * — a worse answer than the truth, and indistinguishable from an uninstall. A * paused site is a fact worth reporting, so it is reported. * * Separated from the POST because the payload is the part worth asserting in a * test and `wp_safe_remote_post` is the part a test cannot arrange, the same split * `equalsites_filter_document` makes for `headers_list()`. */ public static function environment_payload() { $theme = wp_get_theme(); return array( 'wpVersion' => get_bloginfo( 'version' ), 'locale' => get_locale(), 'theme' => $theme->get( 'Name' ) . ' ' . $theme->get( 'Version' ), 'activePlugins' => array_values( (array) get_option( 'active_plugins', array() ) ), 'pluginVersion' => EQUALSITES_VERSION, 'enabled' => equalsites_fixes_enabled(), ); } /** Environment snapshot powering issue→source attribution in the SaaS. */ private static function report_environment( $api_url, $site_id, $token ) { wp_safe_remote_post( $api_url . '/api/sites/' . rawurlencode( $site_id ) . '/environment', array( 'timeout' => 15, 'redirection' => 0, 'headers' => array( 'Authorization' => 'Bearer ' . $token, 'Content-Type' => 'application/json', ), 'body' => wp_json_encode( self::environment_payload() ), ) ); } }