[A-Za-z0-9]{16,128})/(?Pgoal|timer|counter|alerts|actions)', 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' ), 'recent' => array( 'type' => 'integer', 'minimum' => 0, 'maximum' => 1, 'sanitize_callback' => 'absint' ), ), ) ); } /** Read-only. The stored token, or '' when none is configured. Safe for public requests. */ public static function current_token(): string { $token = (string) Settings::get( 'overlay_token', '' ); return strlen( $token ) >= 32 ? $token : ''; } /** * Token for the admin screens; generates one (a DB write) if missing, but ONLY for a user who can manage options. * Public requests must never reach this; they use verify_token(), which never writes. */ public static function ensure_token(): string { if ( ! current_user_can( 'manage_options' ) ) { return ''; } return Settings::ensure_overlay_token(); } /** Read-only compare; with no token configured nothing matches (callers answer 404). */ public static function verify_token( string $given ): bool { $token = self::current_token(); return '' !== $token && hash_equals( $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; $recent = $req->has_param( 'recent' ) && 1 === absint( $req->get_param( 'recent' ) ); $service = new OverlayService( new WpdbDataSource() ); $payload = $service->payload( (string) $req['widget'], time(), $since, $recent ); if ( null === $payload ) { return new \WP_Error( 'sg_not_found', 'Not found.', array( 'status' => 404 ) ); } $etag = Payloads::etag( $payload, $service->etagSalt( (string) $req['widget'] ) ); $headers = array( 'ETag' => $etag, 'Cache-Control' => 'private, max-age=1, must-revalidate', 'X-Robots-Tag' => 'noindex' ) + Build::headers( Build::current() ); $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; } }