` block into ``, * server-side, so crawlers that do not run JavaScript can read it. The content * is fetched from the customer's own Advocate profile, so an owner edit * propagates without anyone touching this site. * * It must NEVER slow down or break the customer's site. Version 1.x did a * synchronous 5-second HTTP call from inside `wp_head` whenever the cache was * cold, and deliberately did not cache failures — so an Advocate outage made * EVERY page view on the customer's site block for up to five seconds, forever, * with no way for them to tell why. That is the defect this rewrite exists to * remove, and it is why the render path below never performs I/O. * * REMOVED IN 2.0.0: the `/.well-known/mcp.json` half. It published a * hand-rolled per-business document whose shape contradicted Advocate's own * canonical server manifest, and it advertised three URLs * (`/query/`, `/agents//card`, `/verify/`) that return 404. * Publishing dead links to crawlers on a customer's domain is worse than * publishing nothing. Advocate's MCP server is a single endpoint discoverable * from Advocate's own domain; it was never per-site. * * ADDED IN 2.4.0: the per-business MCP POINTER. Not a hand-rolled document: * every URL it names is served by Advocate (the central endpoint tagged with * this business's slug, and Advocate's own per-business manifest), so nothing * here can go dead independently of the app. `/.well-known/mcp.json` on this * site is a 302 to that manifest, never a locally generated body. The render * path still performs no I/O. */ defined( 'ABSPATH' ) || exit; define( 'ADVOCATE_OPTION', 'advocate_agent_settings' ); define( 'ADVOCATE_APP_BASE', 'https://app.advocatemcp.com' ); // Keep equal to the `Version:` header above and readme.txt's `Stable tag:`; // scripts/build-plugin-zip.ts refuses to build the zip and manifest otherwise. define( 'ADVOCATE_PLUGIN_VERSION', '2.5.0' ); define( 'ADVOCATE_PLUGIN_FILE', __FILE__ ); // The Settings menu slug. Deliberately NOT renamed in 2.5.0: it is an internal // admin route (not the directory slug, folder, text domain or main file the // review asked to change), and the app's owner links open // `options-general.php?page=advocate-agent` on every copy ever installed — // including the pre-2.5.0 ones no update channel reaches. define( 'ADVOCATE_SETTINGS_PAGE', 'advocate-agent' ); define( 'ADVOCATE_SETUP_IMPORT_OPTION', 'advocate_setup_import' ); define( 'ADVOCATE_SETUP_NOTICE_OPTION', 'advocate_setup_notice' ); define( 'ADVOCATE_LIFECYCLE_OPTION', 'advocate_lifecycle' ); /** How long a good payload is served before a refresh is scheduled. */ define( 'ADVOCATE_TTL', HOUR_IN_SECONDS ); /** Stop publishing without a fully validated 200 in the last 24 hours. */ define( 'ADVOCATE_MAX_STALE', 24 * HOUR_IN_SECONDS ); /** * How long a FAILED fetch is remembered. * * Non-zero on purpose. v1 cached nothing on failure, so every page view retried * a dead endpoint. Ten minutes is short enough that a brief outage self-heals * within one refresh cycle, and long enough that an extended one costs at most * six background requests an hour instead of one per page view. */ define( 'ADVOCATE_FAILURE_TTL', 10 * MINUTE_IN_SECONDS ); /** Bound on the background fetch. Never runs on the page-render path. */ define( 'ADVOCATE_TIMEOUT', 5 ); /** Held while a refresh is in flight so concurrent hits cannot stampede. */ define( 'ADVOCATE_LOCK_TTL', 60 ); const ADVOCATE_CRON_HOOK = 'advocate_refresh_jsonld_event'; // --------------------------------------------------------------------------- // Request values — every superglobal read goes through a WordPress sanitizer // --------------------------------------------------------------------------- /** The request method as the server reported it, upper-cased through sanitize_key(); '' when absent. */ function advocate_request_method() { return isset( $_SERVER['REQUEST_METHOD'] ) ? strtoupper( sanitize_key( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) ) : ''; } /** * The request URI through esc_url_raw(), which keeps a rooted path and its * percent-encoded bytes intact (sanitize_text_field would strip them), or ''. */ function advocate_request_uri() { return isset( $_SERVER['REQUEST_URI'] ) ? esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : ''; } /** The other copy's folder name, derived from this copy's folder. */ function advocate_other_copy_folder( $plugin_dir = null ) { $plugin_dir = is_string( $plugin_dir ) && '' !== $plugin_dir ? $plugin_dir : __DIR__; return 'advocate-agent' === basename( $plugin_dir ) ? 'advocatemcp-structured-data' : 'advocate-agent'; } /** `/.php` of the other copy: what WordPress records in active_plugins and hands to the uninstall hooks. */ function advocate_other_copy_basename() { $other = advocate_other_copy_folder(); return $other . '/' . $other . '.php'; } /** * Whether the other copy of this plugin — the pre-2.5.0 `advocate-agent` folder * or the renamed `advocatemcp-structured-data` folder — is installed beside this * one, judged by its MAIN FILE (an empty leftover folder is not a copy, and a * symlinked plugin folder would make `__DIR__` lie about where the plugins * directory is, so WP_PLUGIN_DIR is preferred when WordPress defines it). Both * copies read the same options and only one can be active, so the * administrator is asked to delete the other. The optional directory is a * testing seam, never a request value. */ function advocate_other_copy_installed( $plugin_dir = null ) { $other = advocate_other_copy_folder( $plugin_dir ); $root = is_string( $plugin_dir ) && '' !== $plugin_dir ? dirname( $plugin_dir ) : ( defined( 'WP_PLUGIN_DIR' ) ? WP_PLUGIN_DIR : dirname( __DIR__ ) ); $main = $root . '/' . $other . '/' . $other . '.php'; clearstatcache( true, $main ); return is_file( $main ); } /** * Whether the other copy is RECORDED active, on this site or network-wide. * `wp plugin activate --skip-plugins` reaches the activation hook * without loading the already-active copy, so no redeclare stops it and both * would be recorded active; every later request would then fatal. */ function advocate_other_copy_active() { $other = advocate_other_copy_basename(); if ( in_array( $other, (array) get_option( 'active_plugins', [] ), true ) ) { return true; } return is_multisite() && array_key_exists( $other, (array) get_site_option( 'active_sitewide_plugins', [] ) ); } // --------------------------------------------------------------------------- // The other copy's uninstall (2.5.0) // // WordPress runs the DELETED copy's own uninstall.php. Every copy before 2.5.0 // removes the shared settings, the one-time import marker, the cached profile // with its lock and health rows, the lifecycle row and the hourly refresh — // with no sibling check. An owner who deletes the old copy while this one is // active would therefore lose the configuration and the site would silently // stop publishing. So, while this copy is active (and only then — nothing here // runs when the old copy is deleted before this one is activated), it keeps // what the other copy's uninstall will delete and puts it back afterwards. The // snapshot key is not among the keys a pre-2.5.0 uninstall deletes, so it // survives that run; a snapshot older than a day is stale (an aborted old // uninstall can leave one behind) and is discarded rather than trusted. // --------------------------------------------------------------------------- define( 'ADVOCATE_SIBLING_SNAPSHOT_OPTION', 'advocate_sibling_snapshot' ); /** A snapshot older than this is stale: it must never resurrect a deleted configuration on a later install. */ define( 'ADVOCATE_SIBLING_SNAPSHOT_TTL', 24 * HOUR_IN_SECONDS ); /** The current snapshot, or null; an expired or malformed one is deleted on sight. */ function advocate_sibling_snapshot() { $snapshot = get_option( ADVOCATE_SIBLING_SNAPSHOT_OPTION, null ); if ( null === $snapshot || false === $snapshot ) { return null; } if ( is_array( $snapshot ) && is_array( $snapshot['options'] ?? null ) && is_int( $snapshot['at'] ?? null ) && time() - $snapshot['at'] <= ADVOCATE_SIBLING_SNAPSHOT_TTL ) { return $snapshot; } delete_option( ADVOCATE_SIBLING_SNAPSHOT_OPTION ); advocate_invalidate_option( ADVOCATE_SIBLING_SNAPSHOT_OPTION ); return null; } /** The options a pre-2.5.0 uninstall.php deletes, for the business configured right now. */ function advocate_sibling_snapshot_keys() { $keys = [ ADVOCATE_OPTION, ADVOCATE_SETUP_IMPORT_OPTION, ADVOCATE_LIFECYCLE_OPTION ]; $slug = advocate_business_slug(); if ( '' !== $slug ) { $keys[] = advocate_payload_key( $slug ); $keys[] = advocate_status_key( $slug ); $keys[] = advocate_lock_key( $slug ); } return $keys; } /** * `pre_uninstall_plugin`: before WordPress includes the OTHER copy's uninstall.php * (core fires this action first, then includes the file), copy what it will * delete into one row. A repeated `pre_uninstall_plugin` must not replace a * snapshot that holds settings with an emptier one. Another plugin's uninstall * is ignored. */ function advocate_snapshot_before_sibling_uninstall( $plugin ) { if ( advocate_other_copy_basename() !== $plugin ) { return; } $missing = new stdClass(); $snapshot = [ 'version' => 1, 'at' => time(), 'options' => [] ]; foreach ( advocate_sibling_snapshot_keys() as $key ) { $value = get_option( $key, $missing ); if ( $value !== $missing ) { $snapshot['options'][ $key ] = $value; } } $existing = advocate_sibling_snapshot(); if ( ! is_array( $snapshot['options'][ ADVOCATE_OPTION ] ?? null ) && null !== $existing ) { return; } update_option( ADVOCATE_SIBLING_SNAPSHOT_OPTION, $snapshot, 'no' ); } /** * Put back what the other copy's uninstall removed and consume the snapshot: * the settings, the import marker, the cached profile and its rows (only where * the row is absent, never over a value written since). Only when at least one * row was re-created does it also write a FRESH lifecycle generation (the old * uninstall set the row inactive and deleted it), reschedule the hourly refresh * and queue a background profile refresh; a sibling that was itself 2.5.0 * removed nothing, and a live worker must not be fenced for nothing. Returns * true only when something was re-created. */ function advocate_restore_after_sibling_uninstall() { $snapshot = advocate_sibling_snapshot(); if ( null === $snapshot ) { return false; } $missing = new stdClass(); $restored = 0; foreach ( $snapshot['options'] as $key => $value ) { if ( ADVOCATE_LIFECYCLE_OPTION === $key ) { continue; } if ( get_option( $key, $missing ) === $missing ) { update_option( $key, $value, ADVOCATE_OPTION === $key ? null : 'no' ); advocate_invalidate_option( $key ); $restored++; } } if ( $restored > 0 ) { update_option( ADVOCATE_LIFECYCLE_OPTION, wp_generate_uuid4(), 'no' ); advocate_invalidate_option( ADVOCATE_LIFECYCLE_OPTION ); if ( ! wp_next_scheduled( ADVOCATE_CRON_HOOK ) ) { wp_schedule_event( time() + 60, 'hourly', ADVOCATE_CRON_HOOK ); } advocate_schedule_background_refresh(); } delete_option( ADVOCATE_SIBLING_SNAPSHOT_OPTION ); advocate_invalidate_option( ADVOCATE_SIBLING_SNAPSHOT_OPTION ); return $restored > 0; } /** * `wp plugin uninstall --skip-delete` runs the other copy's uninstall.php but * never deletes its files, so `deleted_plugin` does not fire. The next load * notices the settings row is gone while a snapshot exists, and restores. A * present settings row — even an empty one — is never overwritten. */ function advocate_restore_on_load() { if ( false !== get_option( ADVOCATE_OPTION, false ) ) { return false; } if ( null === advocate_sibling_snapshot() ) { return false; } return advocate_restore_after_sibling_uninstall(); } add_action( 'pre_uninstall_plugin', 'advocate_snapshot_before_sibling_uninstall' ); add_action( 'deleted_plugin', function ( $plugin ) { if ( advocate_other_copy_basename() === $plugin ) { advocate_restore_after_sibling_uninstall(); } } ); add_action( 'plugins_loaded', 'advocate_restore_on_load' ); add_action( 'admin_notices', function () { if ( ! current_user_can( 'manage_options' ) ) { return; } $screen = get_current_screen(); if ( ! $screen || 'plugins' !== $screen->id || ! advocate_other_copy_installed() ) { return; } echo '

' . esc_html__( 'Two copies of Advocate MCP Structured Data are installed, in the plugin folders "advocate-agent" and "advocatemcp-structured-data": deactivate and delete the one that is not active — your settings carry over, because both copies store them under the same option names.', 'advocatemcp-structured-data' ) . '

'; } ); // --------------------------------------------------------------------------- // Activation / deactivation // --------------------------------------------------------------------------- register_activation_hook( __FILE__, function ( $network_wide = false ) { if ( $network_wide ) { wp_die( esc_html__( 'Activate Advocate separately on each site. Network activation cannot configure one business for every site.', 'advocatemcp-structured-data' ) ); } // Both copies must never be recorded active (see advocate_other_copy_active); refuse before any write. if ( advocate_other_copy_active() ) { wp_die( esc_html__( 'Another copy of Advocate MCP Structured Data is already active, in the other plugin folder ("advocate-agent" or "advocatemcp-structured-data"). Deactivate the other copy, activate this one, and only then delete the other copy; your settings carry over.', 'advocatemcp-structured-data' ) ); } // A new generation fences workers admitted before deactivation/reactivation. $generation = wp_generate_uuid4(); update_option( ADVOCATE_LIFECYCLE_OPTION, $generation, 'no' ); if ( get_option( ADVOCATE_LIFECYCLE_OPTION ) !== $generation ) { wp_die( esc_html__( 'Advocate could not save its activation state. Resolve the WordPress database error and activate again.', 'advocatemcp-structured-data' ) ); } advocate_import_packaged_setup(); if ( ! wp_next_scheduled( ADVOCATE_CRON_HOOK ) ) { wp_schedule_event( time() + 60, 'hourly', ADVOCATE_CRON_HOOK ); } } ); register_deactivation_hook( __FILE__, function ( $network_wide = false ) { if ( ! $network_wide ) { advocate_deactivate_site(); return; } $ids = get_sites( [ 'fields' => 'ids', 'number' => 101, 'network_id' => get_current_network_id(), 'orderby' => 'id', 'order' => 'ASC' ] ); if ( count( $ids ) > 100 ) { wp_die( esc_html__( 'Automatic Advocate network cleanup supports at most 100 sites. No sites were cleaned. Ask your network administrator to follow the per-site WP-CLI cleanup instructions in the plugin readme before removing the plugin files.', 'advocatemcp-structured-data' ) ); } foreach ( $ids as $id ) { switch_to_blog( $id ); try { advocate_deactivate_site(); } finally { restore_current_blog(); } } } ); /** Keep intentional configuration, but remove publishable bytes and old claims. */ function advocate_deactivate_site() { update_option( ADVOCATE_LIFECYCLE_OPTION, 'inactive', 'no' ); if ( 'inactive' !== get_option( ADVOCATE_LIFECYCLE_OPTION ) ) { wp_die( esc_html__( 'Advocate could not save its inactive state. Resolve the WordPress database error and retry cleanup.', 'advocatemcp-structured-data' ) ); } $cleared = wp_clear_scheduled_hook( ADVOCATE_CRON_HOOK ); if ( false === $cleared || is_wp_error( $cleared ) ) { wp_die( esc_html__( 'Advocate could not clear its scheduled tasks. Resolve the WordPress scheduling error and retry cleanup.', 'advocatemcp-structured-data' ) ); } delete_option( ADVOCATE_CONNECT_OPTION ); if ( false !== get_option( ADVOCATE_CONNECT_OPTION, false ) ) { wp_die( esc_html__( 'Advocate could not clear its pending connection. Publishing remains inactive. Resolve the WordPress database error and retry cleanup.', 'advocatemcp-structured-data' ) ); } $slug = advocate_business_slug(); if ( '' === $slug ) { return; } delete_option( advocate_payload_key( $slug ) ); delete_option( advocate_lock_key( $slug ) ); delete_option( advocate_status_key( $slug ) ); delete_transient( advocate_fresh_key( $slug ) ); delete_transient( 'advocate_jsonld_' . $slug ); $missing = new stdClass(); foreach ( [ advocate_payload_key( $slug ), advocate_lock_key( $slug ), advocate_status_key( $slug ) ] as $key ) { if ( get_option( $key, $missing ) !== $missing ) { wp_die( esc_html__( 'Advocate could not remove its cached profile. Publishing remains inactive. Resolve the WordPress database error and retry cleanup.', 'advocatemcp-structured-data' ) ); } } if ( false !== get_transient( advocate_fresh_key( $slug ) ) || false !== get_transient( 'advocate_jsonld_' . $slug ) ) { wp_die( esc_html__( 'Advocate could not remove its cached profile. Publishing remains inactive. Resolve the WordPress cache error and retry cleanup.', 'advocatemcp-structured-data' ) ); } } require_once __DIR__ . '/connect.php'; // Replacing an already-active plugin ZIP does not run its activation hook. // Import on the next administrator request too, never on a visitor's request. add_action( 'admin_init', 'advocate_import_packaged_setup', 5 ); // --------------------------------------------------------------------------- // Optional setup included in an owner-specific download // --------------------------------------------------------------------------- /** * Reduce an HTTP(S) website URL to the identity of a WordPress installation. * * WordPress's public home URL can differ from site_url(), where its core files * live. Compare home_url() and retain the public path so a multisite sibling * under /another-business does not receive this profile. www and HTTPS upgrades * are normal aliases; different subdomains and non-default ports are not. */ function advocate_setup_website_identity( $website ) { if ( ! is_string( $website ) || strlen( $website ) > 2048 ) { return null; } $parts = wp_parse_url( $website ); if ( ! is_array( $parts ) || ! isset( $parts['scheme'], $parts['host'] ) || ! in_array( strtolower( $parts['scheme'] ), [ 'http', 'https' ], true ) || isset( $parts['user'] ) || isset( $parts['pass'] ) || isset( $parts['query'] ) || isset( $parts['fragment'] ) ) { return null; } $host = advocate_normalize_host( $parts['host'] ); if ( ! preg_match( '/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i', $host ) ) { return null; } $port = $parts['port'] ?? null; if ( ( 'http' === strtolower( $parts['scheme'] ) && 80 === $port ) || ( 'https' === strtolower( $parts['scheme'] ) && 443 === $port ) ) { $port = null; } return [ 'host' => $host, 'port' => $port, 'path' => rtrim( $parts['path'] ?? '', '/' ), ]; } /** Validate data, not executable PHP. The archive never carries credentials. */ function advocate_parse_packaged_setup( $raw ) { if ( ! is_string( $raw ) || strlen( $raw ) > 4096 ) { return null; } $config = json_decode( $raw, true ); if ( ! is_array( $config ) || 1 !== ( $config['version'] ?? null ) || ! isset( $config['businessSlug'] ) || ! is_string( $config['businessSlug'] ) || ! preg_match( '/^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$/D', $config['businessSlug'] ) || null === advocate_setup_website_identity( $config['website'] ?? null ) ) { return null; } return $config; } /** * One-time import. Existing choices always win, including a disabled checkbox. * * The marker is deliberately independent of the packaged bytes: clearing or * changing the Business ID must never make an old download configure it again, * even after a plugin update. Deletion removes both this state and the plugin's * files; deliberately installing a newly downloaded package can start afresh. * Invalid/wrong-site packages remain retryable after the owner fixes the source * website and downloads again. No profile request runs within this function. * * The optional file path is an internal testing seam, never a request value. */ function advocate_import_packaged_setup( $file = null ) { if ( ! current_user_can( 'manage_options' ) || get_option( ADVOCATE_SETUP_IMPORT_OPTION, false ) ) { return; } // WordPress passes an empty string to no-argument action callbacks. $file = is_string( $file ) && '' !== $file ? $file : __DIR__ . '/advocate-setup.json'; if ( ! file_exists( $file ) ) { // The generic download intentionally retains the manual settings flow. delete_option( ADVOCATE_SETUP_NOTICE_OPTION ); return; } $raw = is_file( $file ) && is_readable( $file ) ? file_get_contents( $file, false, null, 0, 4097 ) : false; $config = advocate_parse_packaged_setup( $raw ); if ( null === $config ) { update_option( ADVOCATE_SETUP_NOTICE_OPTION, 'invalid', 'no' ); return; } if ( advocate_setup_website_identity( $config['website'] ) !== advocate_setup_website_identity( home_url() ) ) { update_option( ADVOCATE_SETUP_NOTICE_OPTION, 'website_mismatch', 'no' ); return; } // Also acts as an atomic claim if activation and admin_init overlap. if ( ! add_option( ADVOCATE_SETUP_IMPORT_OPTION, 'processed', '', 'no' ) ) { return; } $settings = get_option( ADVOCATE_OPTION, [] ); $has_business = is_array( $settings ) && array_key_exists( 'agent_id', $settings ) && ( ! is_string( $settings['agent_id'] ) || '' !== trim( $settings['agent_id'] ) ); if ( ! is_array( $settings ) || $has_business || ( array_key_exists( 'inject_jsonld', $settings ) && empty( $settings['inject_jsonld'] ) ) ) { $notice = is_array( $settings ) && ( $settings['agent_id'] ?? '' ) === $config['businessSlug'] && advocate_jsonld_enabled() ? 'already_configured' : 'settings_preserved'; update_option( ADVOCATE_SETUP_NOTICE_OPTION, $notice, 'no' ); return; } $settings['agent_id'] = $config['businessSlug']; $settings['inject_jsonld'] = true; // Normalised to what the settings sanitizer stores, so the read-back below // compares like with like whether or not the sanitizer runs on this save. $settings['disable_webmcp'] = ! empty( $settings['disable_webmcp'] ); $GLOBALS['advocate_importing_packaged_setup'] = true; try { update_option( ADVOCATE_OPTION, $settings ); } finally { unset( $GLOBALS['advocate_importing_packaged_setup'] ); } if ( get_option( ADVOCATE_OPTION, [] ) !== $settings ) { delete_option( ADVOCATE_SETUP_IMPORT_OPTION ); update_option( ADVOCATE_SETUP_NOTICE_OPTION, 'save_failed', 'no' ); return; } update_option( ADVOCATE_SETUP_NOTICE_OPTION, 'configured', 'no' ); advocate_schedule_background_refresh(); } add_action( 'admin_notices', function () { if ( ! current_user_can( 'manage_options' ) ) { return; } $screen = get_current_screen(); if ( ! $screen || ! in_array( $screen->id, [ 'plugins', 'settings_page_' . ADVOCATE_SETTINGS_PAGE ], true ) ) { return; } $notice = get_option( ADVOCATE_SETUP_NOTICE_OPTION, '' ); $messages = [ 'configured' => __( 'Advocate is configured for your business. Return to Advocate and select Check connection.', 'advocatemcp-structured-data' ), 'already_configured' => __( 'This business is already configured. Return to Advocate and select Check connection.', 'advocatemcp-structured-data' ), 'settings_preserved' => __( 'Your existing Advocate settings were kept. Open Settings > Advocate to review the business and whether publishing is enabled.', 'advocatemcp-structured-data' ), 'invalid' => __( 'This Advocate download could not be configured automatically. Download the plugin again from Advocate, or open Settings > Advocate to connect manually.', 'advocatemcp-structured-data' ), 'website_mismatch' => __( 'This Advocate download was prepared for a different website. Check your website in Advocate and download again, or open Settings > Advocate to connect manually.', 'advocatemcp-structured-data' ), 'save_failed' => __( 'Advocate could not save the setup. Reload this page to retry, or open Settings > Advocate to connect manually.', 'advocatemcp-structured-data' ), ]; if ( ! isset( $messages[ $notice ] ) ) { return; } $level = in_array( $notice, [ 'configured', 'already_configured' ], true ) ? 'success' : 'warning'; echo '

' . esc_html( $messages[ $notice ] ) . '

'; } ); // --------------------------------------------------------------------------- // Settings accessors // --------------------------------------------------------------------------- /** * The Advocate business slug this site publishes. * * ONE required setting. v1 also demanded an "Agent Query URL" and refused to * work without it, while the admin card that handed out the plugin told the * operator the Business ID alone was enough — so a correctly-followed install * landed on a red "Not configured" banner. The extra field belonged to the * removed MCP half and is gone. */ function advocate_business_slug() { $settings = get_option( ADVOCATE_OPTION, [] ); return trim( $settings['agent_id'] ?? '' ); } /** * Whether the JSON-LD block is enabled. Defaults to ON so a site upgraded from * 1.x, whose saved settings predate this toggle, keeps emitting. */ function advocate_jsonld_enabled() { $settings = get_option( ADVOCATE_OPTION, [] ); return ! array_key_exists( 'inject_jsonld', $settings ) || ! empty( $settings['inject_jsonld'] ); } /** * The last-good cache envelope, in the existing OPTION with no expiry. * * Its freshness clock can expire without expiring the content: once a good * payload exists this site keeps publishing it, * even while Advocate is unreachable, rather than blinking the block out of * every page until the next successful fetch. A stale business description is * far better than none — and "none" is what an expiring cache would give. */ function advocate_payload_key( $slug ) { return 'advocate_jsonld_payload_' . md5( $slug ); } /** * Legacy freshness marker, read only until a flat pre-upgrade payload is * wrapped in the atomic cache envelope. New freshness settles with the payload. * The existing key remains for upgrade and uninstall compatibility. */ function advocate_fresh_key( $slug ) { return 'advocate_jsonld_fresh_' . md5( $slug ); } function advocate_lock_key( $slug ) { return 'advocate_jsonld_lock_' . md5( $slug ); } /** Legacy settings health key; new health lives in the cache envelope. */ function advocate_status_key( $slug ) { return 'advocate_jsonld_status_' . md5( $slug ); } // --------------------------------------------------------------------------- // Fetch — background only // --------------------------------------------------------------------------- /** * Fetch the profile and store it, or store a failure marker. * * Runs from wp-cron, from an explicit admin refresh, and from a shutdown hook * after a page render found the cache empty or stale. It NEVER runs inside * `wp_head`, so no visitor ever waits on Advocate being reachable. * * `surface=injected` re-anchors url/@id to this site's own domain and demotes * the Advocate profile URL to sameAs. Without it the endpoint returns the * hosted arm, which identifies the entity as living on app.advocatemcp.com — * wrong, and actively harmful, in a customer's own . */ /** Read admission state from SQL, never from a potentially stale object cache. */ function advocate_raw_option( $key ) { global $wpdb; return $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1", $key ) ); } /** Direct option writes must invalidate all three WordPress lookup paths. */ function advocate_invalidate_option( $key ) { wp_cache_delete( $key, 'options' ); wp_cache_delete( 'alloptions', 'options' ); wp_cache_delete( 'notoptions', 'options' ); } /** Capture the exact configuration that admitted this fetch. */ function advocate_refresh_scope() { $guard = []; foreach ( [ ADVOCATE_OPTION, 'home', 'siteurl', ADVOCATE_LIFECYCLE_OPTION ] as $key ) { $guard[ $key ] = advocate_raw_option( $key ); advocate_invalidate_option( $key ); } if ( 'inactive' === $guard[ ADVOCATE_LIFECYCLE_OPTION ] ) { return null; } $settings = maybe_unserialize( $guard[ ADVOCATE_OPTION ] ); $slug = is_array( $settings ) && is_string( $settings['agent_id'] ?? null ) ? trim( $settings['agent_id'] ) : ''; $site = advocate_setup_website_identity( home_url() ); if ( '' === $slug || null === $site ) { return null; } return [ 'slug' => $slug, 'site' => $site, 'guard' => $guard ]; } /** * One option holds payload, freshness, response identity and lease. Keeping * them together makes one SQL compare-and-set the settlement boundary, even * on installations whose options table does not support transactions. * A legacy flat payload remains last-good until a valid refresh replaces it. */ function advocate_cache_state( $slug, $site, $value ) { if ( is_array( $value ) && array_key_exists( 'advocate_cache_version', $value ) ) { if ( 1 !== $value['advocate_cache_version'] ) { return null; } if ( ( $value['slug'] ?? null ) === $slug && ( $value['site'] ?? null ) === $site ) { // Older versions checked only the hostname. Recheck stored bytes too, // preserving extension fields for other consumers of this envelope. if ( ! is_array( $value['payload'] ?? null ) || ! advocate_anchors_to_this_site( $value['payload'] ) ) { $value['payload'] = null; } return $value; } $value = null; // A different configured site must not inherit its data. } return [ 'advocate_cache_version' => 1, 'slug' => $slug, 'site' => $site, 'payload' => is_array( $value ) && ! empty( $value ) && advocate_anchors_to_this_site( $value ) ? $value : null, 'identity' => null, 'fresh_until' => 0, 'status' => [], 'lease' => null, ]; } /** * CAS compares bytes, not the database's case-insensitive text collation. * The joined configuration guards also reject settings/site changes between * checking ownership and committing. No transaction spans a provider call. */ function advocate_compare_cache( $scope, $old_raw, $state, $deadline = null ) { global $wpdb; $joins = ''; $guards = ''; $args = []; foreach ( array_keys( $scope['guard'] ) as $i => $key ) { $joins .= "LEFT JOIN $wpdb->options AS cfg$i ON cfg$i.option_name = %s "; $args[] = $key; } $args[] = maybe_serialize( $state ); $args[] = advocate_payload_key( $scope['slug'] ); $args[] = $old_raw; foreach ( array_values( $scope['guard'] ) as $i => $value ) { if ( null === $value ) { $guards .= " AND cfg$i.option_name IS NULL"; } else { $guards .= " AND BINARY cfg$i.option_value = BINARY %s"; $args[] = $value; } } if ( null !== $deadline ) { $guards .= ' AND %d > UNIX_TIMESTAMP()'; $args[] = $deadline; } $sql = "UPDATE $wpdb->options AS target $joins SET target.option_value = %s, target.autoload = 'no' WHERE target.option_name = %s AND BINARY target.option_value = BINARY %s$guards"; // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.PreparedSQL.NotPrepared -- SQL structure uses fixed clauses/trusted WP table names; every value is a prepare placeholder above. $changed = $wpdb->query( $wpdb->prepare( $sql, ...$args ) ); // Delete rather than publish a cached value: an older request must never // replace the cache with its older value after a newer SQL CAS commits. advocate_invalidate_option( advocate_payload_key( $scope['slug'] ) ); return 1 === $changed; } function advocate_claim_refresh() { global $wpdb; $scope = advocate_refresh_scope(); if ( null === $scope ) { return null; } $now = (int) $wpdb->get_var( 'SELECT UNIX_TIMESTAMP()' ); if ( $now <= 0 ) { return null; } // Let a still-live pre-upgrade worker finish. New workers never use the // old standalone lock; old unfenced PHP workers must drain on upgrade. $legacy_lock = advocate_raw_option( advocate_lock_key( $scope['slug'] ) ); if ( is_string( $legacy_lock ) && ctype_digit( $legacy_lock ) && (int) $legacy_lock > $now - ADVOCATE_LOCK_TTL ) { return null; } $key = advocate_payload_key( $scope['slug'] ); $raw = advocate_raw_option( $key ); if ( null === $raw ) { $initial = advocate_cache_state( $scope['slug'], $scope['site'], null ); // IGNORE cannot overwrite a contender, unlike add_option's upsert. $created = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO $wpdb->options (option_name, option_value, autoload) VALUES (%s, %s, 'no')", $key, maybe_serialize( $initial ) ) ); advocate_invalidate_option( $key ); if ( false === $created ) { return null; } $raw = advocate_raw_option( $key ); } if ( null === $raw ) { return null; } $state = advocate_cache_state( $scope['slug'], $scope['site'], maybe_unserialize( $raw ) ); if ( null === $state || ( is_array( $state['lease'] ?? null ) && ( $state['lease']['until'] ?? 0 ) > $now ) ) { return null; } $token = wp_generate_uuid4(); $state['lease'] = [ 'token' => $token, 'until' => $now + ADVOCATE_LOCK_TTL ]; if ( ! advocate_compare_cache( $scope, $raw, $state, $state['lease']['until'] ) ) { return null; } return [ 'scope' => $scope, 'token' => $token ]; } /** An expired/failed owner may release only its own unchanged lease. */ function advocate_release_refresh( $claim ) { $raw = advocate_raw_option( advocate_payload_key( $claim['scope']['slug'] ) ); $state = null === $raw ? null : maybe_unserialize( $raw ); if ( ! is_array( $state ) || ( $state['advocate_cache_version'] ?? null ) !== 1 || ( $state['slug'] ?? null ) !== $claim['scope']['slug'] || ( $state['site'] ?? null ) !== $claim['scope']['site'] || ( $state['lease']['token'] ?? null ) !== $claim['token'] ) { return false; } $state['lease'] = null; return advocate_compare_cache( $claim['scope'], $raw, $state ); } /** Compare canonical decimal revisions without overflowing 32-bit PHP. */ function advocate_compare_revision( $a, $b ) { return strlen( $a ) === strlen( $b ) ? strcmp( $a, $b ) : ( strlen( $a ) < strlen( $b ) ? -1 : 1 ); } function advocate_response_identity( $response ) { $revision = wp_remote_retrieve_header( $response, 'x-advocate-profile-revision' ); $version = wp_remote_retrieve_header( $response, 'x-advocate-representation-version' ); $hash = wp_remote_retrieve_header( $response, 'x-advocate-representation-hash' ); if ( ! is_string( $revision ) || ! preg_match( '/^(?:0|[1-9][0-9]{0,15})$/D', $revision ) || advocate_compare_revision( $revision, '9007199254740991' ) > 0 || ! is_string( $version ) || ! preg_match( '/^jsonld-v[1-9][0-9]{0,5}$/D', $version ) || ! is_string( $hash ) || ! preg_match( '/^[0-9a-f]{64}$/D', $hash ) ) { return null; } return [ 'revision' => $revision, 'version' => $version, 'hash' => $hash ]; } function advocate_refresh_jsonld() { $claim = advocate_claim_refresh(); if ( null === $claim ) { return false; } $slug = $claim['scope']['slug']; try { $url = ADVOCATE_APP_BASE . '/api/biz/' . rawurlencode( $slug ) . '/jsonld?surface=injected'; $response = wp_remote_get( $url, [ 'timeout' => ADVOCATE_TIMEOUT, 'user-agent' => 'AdvocateWordPressPlugin/' . ADVOCATE_PLUGIN_VERSION . ' (+https://app.advocatemcp.com)', 'headers' => [ 'Accept' => 'application/json' ], ] ); return advocate_store_response( $slug, $response, $claim ); } finally { advocate_release_refresh( $claim ); } } /** A late response cannot change either payload or freshness/status. */ function advocate_store_response( $slug, $response, $claim = null ) { global $wpdb; if ( ! is_array( $claim ) || $claim['scope']['slug'] !== $slug ) { return false; } $raw = advocate_raw_option( advocate_payload_key( $slug ) ); $state = null === $raw ? null : maybe_unserialize( $raw ); $now = (int) $wpdb->get_var( 'SELECT UNIX_TIMESTAMP()' ); if ( ! is_array( $state ) || ( $state['advocate_cache_version'] ?? null ) !== 1 || ( $state['slug'] ?? null ) !== $slug || ( $state['site'] ?? null ) !== $claim['scope']['site'] || ( $state['lease']['token'] ?? null ) !== $claim['token'] || ( $state['lease']['until'] ?? 0 ) <= $now || $now <= 0 ) { return false; } $deadline = $state['lease']['until']; $fail = function ( $reason ) use ( $claim, $raw, $state, $now, $deadline ) { $state['fresh_until'] = $now + ADVOCATE_FAILURE_TTL; $state['status'] = [ 'at' => $now, 'ok' => false, 'reason' => $reason ]; $state['lease'] = null; advocate_compare_cache( $claim['scope'], $raw, $state, $deadline ); return false; }; if ( is_wp_error( $response ) ) { return $fail( $response->get_error_message() ); } $code = (int) wp_remote_retrieve_response_code( $response ); // No conditional request was made, so 304 proves nothing about this cache. if ( 200 !== $code ) { /* translators: %d: HTTP response status from the Advocate profile service. */ return $fail( sprintf( __( 'Advocate returned HTTP %d', 'advocatemcp-structured-data' ), $code ) ); } $data = json_decode( wp_remote_retrieve_body( $response ), true ); if ( ! is_array( $data ) || empty( $data ) ) { return $fail( __( 'Advocate returned an empty or unreadable response', 'advocatemcp-structured-data' ) ); } if ( ! advocate_anchors_to_this_site( $data ) ) { return $fail( __( 'Advocate returned a profile anchored to another domain — set your website on Advocate, then refresh.', 'advocatemcp-structured-data' ) ); } $identity = advocate_response_identity( $response ); if ( null === $identity ) { return $fail( __( 'Advocate returned incomplete profile freshness details. Please try again.', 'advocatemcp-structured-data' ) ); } $previous = $state['identity'] ?? null; if ( is_array( $previous ) && ( advocate_compare_revision( $identity['revision'], $previous['revision'] ) < 0 || ( $identity['revision'] === $previous['revision'] && $identity['version'] === $previous['version'] && $identity['hash'] !== $previous['hash'] ) ) ) { return $fail( __( 'Advocate returned an older or inconsistent profile. The last good profile is still in use.', 'advocatemcp-structured-data' ) ); } // A current claim may observe a legitimate pin change at the same revision. // Pins are identities, not ordered numbers; never guess a rollback policy. $state['payload'] = $data; // Use the PHP wall clock here and at render time. SQL time independently // fences the lease; mixing the two clocks for payload age would add DB skew. // This value commits only with the validated payload in the same CAS. $state['validated_at'] = time(); $state['identity'] = $identity; $state['fresh_until'] = $now + ADVOCATE_TTL; $state['status'] = [ 'at' => $now, 'ok' => true, 'id' => is_string( $data['@id'] ?? null ) ? $data['@id'] : ( $data['url'] ?? '' ) ]; $state['lease'] = null; return advocate_compare_cache( $claim['scope'], $raw, $state, $deadline ); } /** Render/settings read remains cache-only and emits no envelope metadata. */ function advocate_cached_profile( $slug ) { $value = get_option( advocate_payload_key( $slug ), null ); $site = advocate_setup_website_identity( home_url() ); $state = advocate_cache_state( $slug, $site, $value ); if ( null === $state ) { return [ 'payload' => null, 'fresh_until' => 0, 'status' => [] ]; } if ( 'inactive' === get_option( ADVOCATE_LIFECYCLE_OPTION ) ) { $state['payload'] = null; return $state; } if ( ! is_array( $value ) || ! array_key_exists( 'advocate_cache_version', $value ) ) { $state['fresh_until'] = false === get_transient( advocate_fresh_key( $slug ) ) ? 0 : time() + 1; $state['status'] = get_option( advocate_status_key( $slug ), [] ); } $now = time(); $validated_at = $state['validated_at'] ?? null; if ( is_array( $state['payload'] ?? null ) && ! empty( $state['payload'] ) && ( ! is_int( $validated_at ) || $validated_at <= 0 || $validated_at > $now || $now - $validated_at >= ADVOCATE_MAX_STALE ) ) { // Suppress at the read boundary even if cron never runs. Do not invent // an upgrade timestamp or extend the deadline on a failed retry. $state['payload'] = null; $state['publication_paused'] = true; } return $state; } /** * True when the payload identifies the entity as living on THIS site. * * The public path and non-default port distinguish sibling installations. * Fragment identifiers name the entity within that site, not another site. * Keep the same www/default-port/HTTPS-upgrade aliases as packaged setup. */ function advocate_anchors_to_this_site( $data ) { $site = advocate_setup_website_identity( home_url() ); if ( ! is_array( $data ) || null === $site ) { return false; } $found = false; foreach ( [ '@id', 'url' ] as $field ) { if ( ! array_key_exists( $field, $data ) ) { continue; } if ( ! is_string( $data[ $field ] ) || '' === $data[ $field ] ) { return false; } $anchor_site = advocate_setup_website_identity( explode( '#', $data[ $field ], 2 )[0] ); if ( null === $anchor_site || $anchor_site !== $site ) { return false; } $found = true; } return $found; } /** The entity URL a payload describes (`@id`, else `url`), for display only. */ function advocate_payload_anchor( $data ) { foreach ( [ '@id', 'url' ] as $field ) { if ( is_array( $data ) && ! empty( $data[ $field ] ) && is_string( $data[ $field ] ) ) { return $data[ $field ]; } } return ''; } /** Lowercase, strip a leading `www.`, drop a trailing dot. */ function advocate_normalize_host( $host ) { if ( ! is_string( $host ) || '' === $host ) { return ''; } $host = strtolower( rtrim( $host, '.' ) ); return preg_replace( '/^www\./', '', $host ); } // --------------------------------------------------------------------------- // Render — no I/O, ever // --------------------------------------------------------------------------- /** * Which pages carry the block. * * A LocalBusiness describing the whole business belongs on pages that represent * the business. v1 emitted it on every front-end page including 404s and search * results, which tells a crawler that a "no results" page IS the business. */ function advocate_should_emit_here() { if ( is_404() || is_search() || is_feed() || is_robots() ) { return false; } return true; } add_action( 'wp_head', function () { if ( ! advocate_jsonld_enabled() || ! advocate_should_emit_here() ) { return; } $slug = advocate_business_slug(); if ( '' === $slug ) { return; } // Stale-while-revalidate. Anything due for a refresh schedules one for AFTER // the response has been sent; the visitor never waits on Advocate being // reachable, which is the whole point of this rewrite. $cached = advocate_cached_profile( $slug ); if ( ( $cached['fresh_until'] ?? 0 ) <= time() ) { advocate_schedule_background_refresh(); } // Emit only site-bound data whose last validated download is under 24h old. // Unknown legacy age or an expired observation withholds publication. $payload = $cached['payload']; if ( ! is_array( $payload ) || empty( $payload ) ) { return; } // JSON_HEX_TAG encodes < and > so a profile value containing "" // cannot break out of the element; the escapes decode back to valid JSON-LD. echo "\n" . '' . "\n"; }, 10 ); /** * Run one refresh after the response is flushed, at most once per request. * * `shutdown` fires after PHP has sent the page, so the visitor is already * served. wp-cron is the primary refresher; this exists so a site with cron * disabled (DISABLE_WP_CRON, or simply no traffic between cron windows) still * self-heals. */ function advocate_schedule_background_refresh() { static $scheduled = false; if ( $scheduled ) { return; } $scheduled = true; add_action( 'shutdown', 'advocate_refresh_jsonld', 100 ); } add_action( ADVOCATE_CRON_HOOK, 'advocate_refresh_jsonld' ); // Re-fetch immediately when the slug changes, so an operator correcting a typo // sees the result on the settings page rather than waiting for the next cron. function advocate_clear_previous_business_cache( $old_slug, $new_slug ) { if ( '' !== $old_slug && $old_slug !== $new_slug ) { delete_transient( advocate_fresh_key( $old_slug ) ); delete_option( advocate_payload_key( $old_slug ) ); delete_option( advocate_status_key( $old_slug ) ); delete_option( advocate_lock_key( $old_slug ) ); delete_transient( 'advocate_jsonld_' . $old_slug ); } } add_action( 'update_option_' . ADVOCATE_OPTION, function ( $old, $new ) { // A local edit invalidates every pending/replayed browser handoff, including ABA edits. delete_option( ADVOCATE_CONNECT_OPTION ); $old_slug = trim( is_array( $old ) ? ( $old['agent_id'] ?? '' ) : '' ); $new_slug = trim( is_array( $new ) ? ( $new['agent_id'] ?? '' ) : '' ); if ( $old_slug !== $new_slug ) { advocate_clear_previous_business_cache( $old_slug, $new_slug ); if ( ! empty( $GLOBALS['advocate_importing_packaged_setup'] ) ) { advocate_schedule_background_refresh(); } else { advocate_refresh_jsonld(); } } }, 10, 2 ); // --------------------------------------------------------------------------- // Traffic beacon (2.1.0) — the visitor never waits, the raw IP never leaves // --------------------------------------------------------------------------- /** * Tell Advocate one front-end page view happened, carrying the VISITOR's * user agent — so AI crawlers reading this site become visible on the * owner's Advocate dashboard, the same way the Cloudflare-connector rail's * are. Same contract as the JSON-LD refresh: * * - Fires on `shutdown`, AFTER the response is flushed, and the request is * non-blocking with a hard timeout, so a visitor never waits on Advocate * being reachable — the same rule the whole 2.x rewrite exists for. * - Fires only on renders the block itself targets (enabled + slug set + * advocate_should_emit_here()), so 404s/search/feeds beacon nothing. * - The raw client IP never leaves this server: it is reduced to an * unkeyed SHA-256 here, matching what the Cloudflare connector sends. * - Fail-open and silent. A beacon failure must never surface anywhere — * no admin notice, no log spam, no retry queue. * * KNOWN LIMIT, stated rather than hidden: a page served from a page cache * (Breeze, Varnish, etc.) never runs PHP, so cached views fire no beacon. * The numbers Advocate shows from this are a floor, not a census. */ function advocate_send_traffic_beacon() { if ( 'inactive' === get_option( ADVOCATE_LIFECYCLE_OPTION ) ) { return; } $slug = advocate_business_slug(); if ( '' === $slug ) { return; } $host = advocate_normalize_host( wp_parse_url( home_url(), PHP_URL_HOST ) ); if ( '' === $host ) { return; } $request_uri = advocate_request_uri(); if ( '' === $request_uri ) { $request_uri = '/'; } // Path only — the query string can carry junk an unauthenticated // aggregate should never store. wp_parse_url copes with a full URI. $path = wp_parse_url( $request_uri, PHP_URL_PATH ); if ( ! is_string( $path ) || '' === $path || '/' !== $path[0] ) { $path = '/'; } $path = substr( $path, 0, 1024 ); $user_agent = isset( $_SERVER['HTTP_USER_AGENT'] ) ? substr( sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ), 0, 1024 ) : ''; $body = [ 'slug' => $slug, 'host' => $host, 'path' => $path, 'userAgent' => $user_agent, // Self-reported, so Advocate can show which plugin version a site runs. Same // trust class as the rest of this body: host-attested, not authenticated. 'pluginVersion' => ADVOCATE_PLUGIN_VERSION, ]; $ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : ''; // Only a real address is hashed; anything else is dropped rather than hashed as if it were one. if ( '' !== $ip && false !== filter_var( $ip, FILTER_VALIDATE_IP ) ) { $body['ipHash'] = hash( 'sha256', $ip ); } wp_remote_post( ADVOCATE_APP_BASE . '/api/edge/plugin-beacon', [ 'timeout' => 2, 'blocking' => false, 'headers' => [ 'content-type' => 'application/json' ], 'body' => wp_json_encode( $body ), 'user-agent' => 'AdvocateWordPressPlugin/' . ADVOCATE_PLUGIN_VERSION . ' (+https://app.advocatemcp.com)', ] ); } /** Arm the beacon for this request, at most once. */ function advocate_schedule_traffic_beacon() { static $scheduled = false; if ( $scheduled ) { return; } $scheduled = true; add_action( 'shutdown', 'advocate_send_traffic_beacon', 101 ); } // Armed from wp_head at priority 11 — after the render callback above, under // exactly its gate: injection enabled, slug configured, a page the block // itself targets. Whether the payload option held bytes THIS request does // not gate the beacon (mirrors the connector, which beacons every page view // it ATTEMPTS injection into). add_action( 'wp_head', function () { if ( ! advocate_jsonld_enabled() || ! advocate_should_emit_here() ) { return; } if ( '' === advocate_business_slug() ) { return; } advocate_schedule_traffic_beacon(); }, 11 ); // --------------------------------------------------------------------------- // Per-business MCP pointer (2.4.0) — no I/O, ever // --------------------------------------------------------------------------- /** Advocate's MCP endpoint; `business` and `via` query tags attribute a call to this site. */ define( 'ADVOCATE_MCP_ENDPOINT', 'https://api.advocatemcp.com/mcp' ); // What the server serves for this business, worded to be true for every // business. Identical to MCP_SERVED_SCOPE / MCP_CONDITIONAL_SCOPE in the app. define( 'ADVOCATE_MCP_SERVED_SCOPE', 'the services and prices, credentials, cancellation policy and booking route the business has published' ); define( 'ADVOCATE_MCP_CONDITIONAL_SCOPE', 'where the business has set it up, assistants can also check open appointment times and send booking requests' ); function advocate_mcp_endpoint_url( $slug, $via ) { return ADVOCATE_MCP_ENDPOINT . '?business=' . rawurlencode( $slug ) . '&via=' . rawurlencode( $via ); } function advocate_mcp_manifest_url( $slug, $via = '' ) { $url = ADVOCATE_APP_BASE . '/biz/' . rawurlencode( $slug ) . '/mcp.json'; return '' === $via ? $url : $url . '?via=' . rawurlencode( $via ); } /** * The slug the pointer may name on THIS request, or ''. Exactly the JSON-LD * block's gate plus a validated, site-anchored payload: the pointer is * published only where the profile itself is. */ function advocate_pointer_slug( $require_page_gate = true ) { if ( ! advocate_jsonld_enabled() || ( $require_page_gate && ! advocate_should_emit_here() ) ) { return ''; } $slug = advocate_business_slug(); if ( '' === $slug ) { return ''; } $payload = advocate_cached_profile( $slug )['payload']; return is_array( $payload ) && ! empty( $payload ) ? $slug : ''; } /** ``, `` and the WebAPI JSON-LD node. */ function advocate_agent_pointer_html( $slug ) { $manifest = advocate_mcp_manifest_url( $slug ); $node = [ '@context' => 'https://schema.org', '@type' => 'WebAPI', '@id' => $manifest . '#webapi', 'name' => 'Business details over MCP', 'description' => 'Model Context Protocol (JSON-RPC 2.0 over Streamable HTTP, no sign-in) serving ' . ADVOCATE_MCP_SERVED_SCOPE . '; ' . ADVOCATE_MCP_CONDITIONAL_SCOPE . '. Business-scoped tools take the argument slug="' . $slug . '".', 'url' => advocate_mcp_endpoint_url( $slug, 'wp.jsonld' ), 'documentation' => $manifest, 'provider' => [ '@type' => 'Organization', 'name' => 'Advocate', 'url' => ADVOCATE_APP_BASE ], // An IRI reference to the hosted profile, never a typed stub a merging parser would read as a second LocalBusiness. 'about' => ADVOCATE_APP_BASE . '/biz/' . rawurlencode( $slug ), 'potentialAction' => [ '@type' => 'Action', 'name' => 'Call an MCP tool for this business', 'target' => [ '@type' => 'EntryPoint', 'urlTemplate' => advocate_mcp_endpoint_url( $slug, 'wp.jsonld' ), 'httpMethod' => 'POST', 'contentType' => 'application/json', 'encodingType' => 'application/json', ], ], ]; return "\n" . '' . "\n" . '' . "\n" . '' . "\n" . '' . "\n"; } /** RFC 8288 Link value: the endpoint, then the manifest. */ function advocate_agent_pointer_link_header( $slug ) { return '<' . advocate_mcp_endpoint_url( $slug, 'wp.link-header' ) . '>; rel="mcp-server https://app.advocatemcp.com/rel/mcp-endpoint"; type="application/json", ' . '<' . advocate_mcp_manifest_url( $slug ) . '>; rel="service-desc"; type="application/json"'; } /** * Where a GET/HEAD for this site's `/.well-known/mcp.json` redirects — the * app's manifest tagged for this rail — or null. Exact path, query ignored. * Fires only when WordPress would otherwise answer 404 (is_404(), settled by * template_redirect), and its hook runs at the LAST template_redirect * priority, so it never pre-empts: a static file (answered by the web server * before WordPress runs), anything WordPress routes to a non-404 (a page, * another plugin's rewrite), and any other template_redirect handler that * serves the path. Not covered: something that serves the path only later, * from template_include, a 404_template filter or the theme's 404.php. On a * site that shows the home page for unknown paths (plain permalinks behind a * catch-all server rule) nothing is a 404, so the redirect never fires. The * page gate is skipped because that 404 is exactly the case being handled. */ function advocate_agent_manifest_redirect_target() { if ( ! is_404() ) { return null; } $method = advocate_request_method(); if ( 'GET' !== $method && 'HEAD' !== $method ) { return null; } $request_uri = advocate_request_uri(); if ( '/.well-known/mcp.json' !== strtok( $request_uri, '?' ) ) { return null; } $slug = advocate_pointer_slug( false ); return '' === $slug ? null : advocate_mcp_manifest_url( $slug, 'wp.well-known' ); } // Priority 12: after the JSON-LD block (10) and the beacon arm (11), so the // representation stays the first script in . add_action( 'wp_head', function () { $slug = advocate_pointer_slug(); if ( '' !== $slug ) { // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Every input to advocate_agent_pointer_html() is escaped there: attribute values through esc_attr(), the JSON-LD node through wp_json_encode() with JSON_HEX_TAG; the tags themselves are fixed literals. wp_kses() is the wrong tool for this output because it entity-encodes the JSON (& becomes &) and breaks the structured data. echo advocate_agent_pointer_html( $slug ); } }, 12 ); // template_redirect runs after handle_404, so is_404() is settled here (it is // not yet at send_headers). The pointer Link header goes out at the default // priority; the well-known redirect waits for every other template_redirect // handler (PHP_INT_MAX) so it can never pre-empt one that serves the path. add_action( 'template_redirect', function () { $slug = advocate_pointer_slug(); if ( '' !== $slug && ! headers_sent() ) { header( 'Link: ' . advocate_agent_pointer_link_header( $slug ), false ); } } ); add_action( 'template_redirect', function () { $target = advocate_agent_manifest_redirect_target(); if ( null !== $target ) { wp_redirect( $target, 302 ); exit; } }, PHP_INT_MAX ); // --------------------------------------------------------------------------- // Conflict detection // --------------------------------------------------------------------------- /** * Other SEO plugins that emit their own LocalBusiness/Organization JSON-LD. * * Two blocks describing one business on one page is a real risk — the customer * we built this for runs Rank Math. v1's entire answer was a checkbox that * defaults to ON and a sentence asking the owner to think about it. This names * the conflict on screen instead. */ function advocate_detect_schema_conflict() { $known = [ 'wordpress-seo/wp-seo.php' => 'Yoast SEO', 'seo-by-rank-math/rank-math.php' => 'Rank Math', 'wp-seopress/seopress.php' => 'SEOPress', 'all-in-one-seo-pack/all_in_one_seo_pack.php' => 'All in One SEO', 'schema-and-structured-data-for-wp/structured-data-for-wp.php' => 'Schema & Structured Data for WP', ]; // `is_plugin_active` lives in an admin include that is not loaded on every // screen. Calling it unguarded is a fatal error, and a fatal on the settings // page is exactly the kind of thing a customer sees and we do not. if ( ! function_exists( 'is_plugin_active' ) ) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; } $found = []; foreach ( $known as $file => $label ) { if ( is_plugin_active( $file ) ) { $found[] = $label; } } return $found; } // --------------------------------------------------------------------------- // Admin // --------------------------------------------------------------------------- /** * "Refresh now". The redirect reports what the refresh actually did. * * `advocate_refresh_jsonld()` returns true only when a response was fetched, * validated against this site and this profile's revision history, and stored * by the SQL compare-and-set. A busy lease, a missing Business ID, a failed or * wrong-site response, or a settlement rejected by the compare-and-set all * return false — and each one leaves the last-good cache exactly as it was. * Earlier versions redirected with `advocate_refreshed=1` unconditionally, so * the settings page announced "Refreshed" after every one of those outcomes. * * A successful refresh replaces this plugin's own cache. It does not clear a * full-page or CDN cache in front of this site, and the settings page says so. */ add_action( 'admin_post_advocate_refresh_jsonld', function () { if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'Insufficient permissions.', 'advocatemcp-structured-data' ) ); } check_admin_referer( 'advocate_refresh_jsonld' ); $slug = advocate_business_slug(); $accepted = false; if ( '' !== $slug ) { delete_transient( advocate_fresh_key( $slug ) ); $accepted = true === advocate_refresh_jsonld(); } wp_safe_redirect( add_query_arg( [ 'page' => ADVOCATE_SETTINGS_PAGE, 'advocate_refreshed' => $accepted ? '1' : '0' ], admin_url( 'options-general.php' ) ) ); exit; } ); add_action( 'admin_menu', function () { add_options_page( __( 'Advocate MCP Structured Data', 'advocatemcp-structured-data' ), __( 'Advocate', 'advocatemcp-structured-data' ), 'manage_options', ADVOCATE_SETTINGS_PAGE, 'advocate_settings_page' ); } ); add_action( 'admin_init', function () { register_setting( ADVOCATE_OPTION, ADVOCATE_OPTION, [ 'sanitize_callback' => function ( $input ) { if ( empty( $GLOBALS['advocate_importing_packaged_setup'] ) ) { delete_option( ADVOCATE_CONNECT_OPTION ); // Manual changes are intentional. A stale package must never // restore a cleared ID or turn publishing back on afterward. add_option( ADVOCATE_SETUP_IMPORT_OPTION, 'processed', '', 'no' ); delete_option( ADVOCATE_SETUP_NOTICE_OPTION ); } return [ 'agent_id' => sanitize_text_field( trim( $input['agent_id'] ?? '' ) ), 'inject_jsonld' => ! empty( $input['inject_jsonld'] ), // Directory UI has no script control; retain the stored preference. 'disable_webmcp' => ! empty( get_option( ADVOCATE_OPTION, [] )['disable_webmcp'] ), ]; }, ] ); } ); /** * The settings page describes what THIS SITE IS DOING, not the last attempt. * * Three facts decide the status block, read from the same cache envelope the * head renderer prints from: whether injection is switched on, whether a * last-good payload exists, and whether the latest attempt succeeded. The * earlier page read the attempt status alone, so a site still serving its * last-good profile after one failed check was told "Not publishing … nothing * is added", and a site with injection switched off was told "Publishing". * * slug empty → set-up instruction (unchanged) * injection off → "Publishing is off." — never "Publishing" * payload + latest attempt ok → "Publishing." with the factual last download (unchanged) * payload + latest attempt failed → "Using your last saved profile." + the escaped reason * payload, no attempt recorded → "Publishing." (legacy cache; no download time is invented) * no payload + an attempt failed → "Profile not added yet." + the escaped reason * no payload, nothing recorded → waiting for the first successful download */ function advocate_settings_page() { $slug = advocate_business_slug(); $enabled = advocate_jsonld_enabled(); $cached = '' !== $slug ? advocate_cached_profile( $slug ) : [ 'payload' => null, 'status' => [] ]; $status = is_array( $cached['status'] ?? null ) ? $cached['status'] : []; $has_payload = is_array( $cached['payload'] ?? null ) && ! empty( $cached['payload'] ); $last_ok = ! empty( $status['ok'] ); $reason = is_string( $status['reason'] ?? null ) && '' !== $status['reason'] ? $status['reason'] : __( 'The last fetch from Advocate failed.', 'advocatemcp-structured-data' ); $conflicts = advocate_detect_schema_conflict(); $profile = '' !== $slug ? ADVOCATE_APP_BASE . '/biz/' . rawurlencode( $slug ) : ''; // The query value is presentation only; the refresh itself already happened // (or did not) inside the nonce-checked handler above. // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Display-only flag from this plugin's own nonce-checked refresh redirect; reading it changes nothing. $refreshed = isset( $_GET['advocate_refreshed'] ) ? ( '1' === sanitize_key( wp_unslash( $_GET['advocate_refreshed'] ) ) ? 'accepted' : 'unsuccessful' ) : null; ?>

' . esc_html( $status['id'] ?? '' ) . '', esc_html( human_time_diff( (int) ( $status['at'] ?? time() ) ) ) ); ?>

' . esc_html( advocate_payload_anchor( $cached['payload'] ) ) . '' ); ?>