/?accessnow_replica_api=1 * B POST ?action=accessnow_replica_api * C POST * This site tells the other one the addresses of B and C (Connection_Keys::endpoints()). * * @package AccessNow\Replica */ namespace AccessNow\Replica; use AccessNow\Replica\Source\Api; use AccessNow\Replica\Source\Guard_Error; use AccessNow\Replica\Source\Request_Guard; defined( 'ABSPATH' ) || exit; /** * Early request routing. */ final class Early_Dispatcher { /** * Hooks. */ public static function init() { add_action( 'plugins_loaded', array( __CLASS__, 'maybe_dispatch' ), -1000 ); } /** * Whether this request is for the source API. */ public static function is_api_request() { // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Routing only; the guard authenticates. if ( 'POST' !== ( isset( $_SERVER['REQUEST_METHOD'] ) ? strtoupper( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) ) : '' ) ) { return false; } if ( isset( $_GET['accessnow_replica_api'] ) ) { return true; } if ( wp_doing_ajax() && isset( $_REQUEST['action'] ) && 'accessnow_replica_api' === sanitize_key( wp_unslash( $_REQUEST['action'] ) ) ) { return true; } if ( isset( $_GET['rest_route'] ) && '/site-replica/v1/api' === untrailingslashit( sanitize_text_field( wp_unslash( $_GET['rest_route'] ) ) ) ) { return true; } $uri = isset( $_SERVER['REQUEST_URI'] ) ? (string) wp_parse_url( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ), PHP_URL_PATH ) : ''; // phpcs:enable WordPress.Security.NonceVerification.Recommended $rest = '/' . trim( rest_get_url_prefix(), '/' ) . '/site-replica/v1/api'; return '' !== $uri && substr( untrailingslashit( $uri ), -strlen( $rest ) ) === $rest; } /** * Handles API requests; everything else continues normally. */ public static function maybe_dispatch() { if ( ! self::is_api_request() ) { return; } if ( ! defined( 'DONOTCACHEPAGE' ) ) { define( 'DONOTCACHEPAGE', true ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound -- Standard constant read by caching plugins. } if ( function_exists( 'wp_set_current_user' ) ) { wp_set_current_user( 0 ); } try { list( $env, $key ) = Request_Guard::check(); } catch ( Guard_Error $e ) { $body = array( 'error' => $e->error_code, 'message' => 'not_found' === $e->error_code ? '' : $e->getMessage(), ); Api::send( $e->status, (string) wp_json_encode( $body + $e->data ), 'application/json; charset=utf-8' ); } catch ( \Throwable $e ) { Logger::audit( 'Guard failure.', array( 'error' => $e->getMessage() ) ); Api::send( 500, (string) wp_json_encode( array( 'error' => 'server_error', 'message' => 'The source site hit an error. Check its PHP error log.' ) ), 'application/json; charset=utf-8' ); } Api::serve( $env, $key ); } }