[A-Za-z0-9]{16,128})/(?Pgoal|timer|counter|alerts)', array( 'methods' => 'GET', 'callback' => array( self::class, 'handle' ), 'permission_callback' => '__return_true', // capability is the unguessable token, checked in handle() 'args' => array( 'since' => array( 'type' => 'integer', 'minimum' => 0, 'sanitize_callback' => 'absint' ), ), ) ); } /** Lazily generates the token (32 hex chars) on first use. */ public static function token(): string { $token = (string) Settings::get( 'overlay_token', '' ); if ( strlen( $token ) < 32 ) { $token = bin2hex( random_bytes( 16 ) ); Settings::update( array( 'overlay_token' => $token ) ); } return $token; } public static function verify_token( string $given ): bool { return hash_equals( self::token(), $given ); } public static function handle( \WP_REST_Request $req ): \WP_REST_Response|\WP_Error { if ( ! self::verify_token( (string) $req['token'] ) ) { return new \WP_Error( 'sg_not_found', 'Not found.', array( 'status' => 404 ) ); } $since = $req->has_param( 'since' ) && '' !== (string) $req->get_param( 'since' ) ? absint( $req->get_param( 'since' ) ) : null; $payload = ( new OverlayService( new WpdbDataSource() ) )->payload( (string) $req['widget'], time(), $since ); if ( null === $payload ) { return new \WP_Error( 'sg_not_found', 'Not found.', array( 'status' => 404 ) ); } $etag = Payloads::etag( $payload ); $headers = array( 'ETag' => $etag, 'Cache-Control' => 'private, max-age=1, must-revalidate', 'X-Robots-Tag' => 'noindex' ); $inm = (string) $req->get_header( 'if_none_match' ); if ( '' !== $inm && in_array( $etag, array_map( 'trim', explode( ',', str_replace( 'W/', '', $inm ) ) ), true ) ) { $res = new \WP_REST_Response( null, 304 ); } else { $res = new \WP_REST_Response( $payload, 200 ); } foreach ( $headers as $k => $v ) { $res->header( $k, $v ); } return $res; } }