// Truncate path at help depth.
// @phan-suppress-next-line PhanPossiblyUndeclaredVariable -- $depth is set when $is_help is true.
$endpoint_path = implode( '/', array_slice( explode( '/', $endpoint_path ), 0, $depth ) );
// Generate regular expression from sprintf().
$endpoint_path_regex = str_replace( array( '%s', '%d' ), array( '([^/?&]+)', '(\d+)' ), $endpoint_path );
if ( ! preg_match( "#^$endpoint_path_regex\$#", $this->path, $path_pieces ) ) {
// This endpoint does not match the requested path.
if ( version_compare( $this->version, $endpoint_min_version, '<' ) || version_compare( $this->version, $endpoint_max_version, '>' ) ) {
// This endpoint does not match the requested version.
if ( $find_all_matching_endpoints ) {
$matching_endpoints[] = array( $endpoints_by_method[ $method ], $path_pieces );
// The method parameters are now in $path_pieces.
$endpoint = $endpoints_by_method[ $method ];
return $this->output( 404, '', 'text/plain' );
$allowed_methods = array();
foreach ( $matching_endpoints as $matching_endpoint ) {
$allowed_methods[] = $matching_endpoint[0]->method;
header( 'Allow: ' . strtoupper( implode( ',', array_unique( $allowed_methods ) ) ) );
'error' => 'not_allowed',
'error_message' => 'Method not allowed',
* Fires before the API output.
do_action( 'wpcom_json_api_output', 'help' );
$proxied = function_exists( 'wpcom_is_proxied_request' ) ? wpcom_is_proxied_request() : false;
// @phan-suppress-next-line PhanPossiblyUndeclaredVariable -- $help_content_type is set when $is_help is true.
if ( 'json' === $help_content_type ) {
foreach ( $matching_endpoints as $matching_endpoint ) {
if ( $matching_endpoint[0]->is_publicly_documentable() || $proxied || WPCOM_JSON_API__DEBUG ) {
$docs[] = call_user_func( array( $matching_endpoint[0], 'generate_documentation' ) );
return $this->output( 200, $docs );
foreach ( $matching_endpoints as $matching_endpoint ) {
if ( $matching_endpoint[0]->is_publicly_documentable() || $proxied || WPCOM_JSON_API__DEBUG ) {
call_user_func( array( $matching_endpoint[0], 'document' ) );
// @phan-suppress-next-line PhanPossiblyUndeclaredVariable -- $endpoint is set when $find_all_matching_endpoints is false and $found is true, which is guaranteed here.
if ( $endpoint->in_testing && ! WPCOM_JSON_API__DEBUG ) {
return $this->output( 404, '', 'text/plain' );
/** This action is documented in class.json-api.php */
// @phan-suppress-next-line PhanPossiblyUndeclaredVariable -- $endpoint is set when $find_all_matching_endpoints is false and $found is true, which is guaranteed here.
do_action( 'wpcom_json_api_output', $endpoint->stat );
// @phan-suppress-next-line PhanPossiblyUndeclaredVariable -- $endpoint is set when $find_all_matching_endpoints is false and $found is true, which is guaranteed here.
$response = $this->process_request( $endpoint, $path_pieces );
if ( ! $response && ! is_array( $response ) ) {
return $this->output( 500, '', 'text/plain' );
} elseif ( is_wp_error( $response ) ) {
return $this->output_error( $response );
$output_status_code = $this->output_status_code;
$this->set_output_status_code();
return $this->output( $output_status_code, $response, 'application/json', $this->extra_headers );
* @param WPCOM_JSON_API_Endpoint $endpoint Endpoint.
* @param array $path_pieces Path pieces.
* @return array|WP_Error Return value from the endpoint's callback.
public function process_request( WPCOM_JSON_API_Endpoint $endpoint, $path_pieces ) {
$this->endpoint = $endpoint;
$this->maybe_switch_to_token_user_and_site();
return call_user_func_array( array( $endpoint, 'callback' ), $path_pieces );
* Output a response or error without exiting.
* @param int $status_code HTTP status code.
* @param mixed $response Response data.
* @param string $content_type Content type of the response.
public function output_early( $status_code, $response = null, $content_type = 'application/json' ) {
if ( is_wp_error( $response ) ) {
$this->output_error( $response );
$this->output( $status_code, $response, $content_type );
if ( ! defined( 'XMLRPC_REQUEST' ) || ! XMLRPC_REQUEST ) {
* Set output status code.
* @param int $code HTTP status code.
public function set_output_status_code( $code = 200 ) {
$this->output_status_code = $code;
* @param int $status_code HTTP status code.
* @param mixed $response Response data.
* @param string $content_type Content type of the response.
* @param array $extra Additional HTTP headers.
* @return string Content type (assuming it didn't exit).
public function output( $status_code, $response = null, $content_type = 'application/json', $extra = array() ) {
$status_code = (int) $status_code;
// In case output() was called before the callback returned.
if ( $this->did_output ) {
$this->did_output = true;
// 400s and 404s are allowed for all origins
if ( 404 === $status_code || 400 === $status_code ) {
header( 'Access-Control-Allow-Origin: *' );
/* Add headers for form submission from <amp-form/> */
if ( $this->amp_source_origin ) {
header( 'Access-Control-Allow-Origin: ' . wp_unslash( $this->amp_source_origin ) );
header( 'Access-Control-Allow-Credentials: true' );
if ( $response === null ) {
$response = new stdClass();
if ( 'text/plain' === $content_type ||
'text/html' === $content_type ) {
status_header( $status_code );
header( 'Content-Type: ' . $content_type );
foreach ( $extra as $key => $value ) {
header( "$key: $value" );
echo $response; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
$response = $this->filter_fields( $response );
if ( isset( $this->query['http_envelope'] ) && self::is_truthy( $this->query['http_envelope'] ) ) {
$response = static::wrap_http_envelope( $status_code, $response, $content_type, $extra );
$content_type = 'application/json';
status_header( $status_code );
header( "Content-Type: $content_type" );
if ( isset( $this->query['callback'] ) && is_string( $this->query['callback'] ) ) {
$callback = preg_replace( '/[^a-z0-9_.]/i', '', $this->query['callback'] );
// Mitigate Rosetta Flash [1] by setting the Content-Type-Options: nosniff header
// and by prepending the JSONP response with a JS comment.
// [1] <https://blog.miki.it/2014/7/8/abusing-jsonp-with-rosetta-flash/index.html>.
echo "/**/$callback("; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- This is JSONP output, not HTML.
echo $this->json_encode( $response, JSON_UNESCAPED_SLASHES ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- This is JSON or JSONP output, not HTML.
* Wrap JSON API response into an HTTP 200 one.
* @param int $status_code HTTP status code.
* @param mixed $response Response body.
* @param string $content_type Content type.
* @param array|null $extra Extra data.
public static function wrap_http_envelope( $status_code, $response, $content_type, $extra = null ) {
'name' => 'Content-Type',
'value' => $content_type,
if ( is_array( $extra ) ) {
foreach ( $extra as $key => $value ) {
'code' => (int) $status_code,
* @param WP_Error $error Error.
* @return array with 'status_code' and 'errors' data.
public static function serializable_error( $error ) {
$status_code = $error->get_error_data();
if ( is_array( $status_code ) && isset( $status_code['status_code'] ) ) {
$status_code = $status_code['status_code'];
'error' => $error->get_error_code(),
'message' => $error->get_error_message(),
$additional_data = $error->get_error_data( 'additional_data' );
if ( $additional_data ) {
$response['data'] = $additional_data;
'status_code' => $status_code,
* @param WP_Error $error Error.
* @return string Content type (assuming it didn't exit).
public function output_error( $error ) {
$error_response = static::serializable_error( $error );
return $this->output( $error_response['status_code'], $error_response['errors'] );
* Filter fields in a response.
* @param array|object $response Response.
* @return array|object Filtered response.
public function filter_fields( $response ) {
if ( empty( $this->query['fields'] ) || ( is_array( $response ) && ! empty( $response['error'] ) ) || ! empty( $this->endpoint->custom_fields_filtering ) ) {
$fields = array_map( 'trim', explode( ',', $this->query['fields'] ) );
if ( is_object( $response ) ) {
$response = (array) $response;
if ( is_array( $response ) && empty( $response['ID'] ) ) {
foreach ( $keys_to_filter as $key_to_filter ) {
if ( ! isset( $response[ $key_to_filter ] ) || $has_filtered ) {
foreach ( $response[ $key_to_filter ] as $key => $values ) {
if ( is_object( $values ) ) {
if ( is_object( $response[ $key_to_filter ] ) ) {
// phpcs:ignore Squiz.PHP.DisallowMultipleAssignments.Found -- False positive.
$response[ $key_to_filter ]->$key = (object) array_intersect_key( ( (array) $values ), array_flip( $fields ) );
} elseif ( is_array( $response[ $key_to_filter ] ) ) {
$response[ $key_to_filter ][ $key ] = (object) array_intersect_key( ( (array) $values ), array_flip( $fields ) );
} elseif ( is_array( $values ) ) {
$response[ $key_to_filter ][ $key ] = array_intersect_key( $values, array_flip( $fields ) );
if ( is_object( $response ) ) {
$response = (object) array_intersect_key( (array) $response, array_flip( $fields ) );
} elseif ( is_array( $response ) ) {
$response = array_intersect_key( $response, array_flip( $fields ) );
* If `$original_scheme` is null, turns an https URL to http.
* @param string $url The complete home URL including scheme and path.
* @param string $path Path relative to the home URL. Blank string if no path is specified.
* @param string|null $original_scheme Scheme to give the home URL context. Accepts 'http', 'https', 'relative', 'rest', or null.
public function ensure_http_scheme_of_home_url( $url, $path, $original_scheme ) {
if ( $original_scheme ) {
return preg_replace( '#^https:#', 'http:', $url );
* Decode HTML special characters in comment content.
* @param string $comment_content Comment content.
public function comment_edit_pre( $comment_content ) {
return htmlspecialchars_decode( $comment_content, ENT_QUOTES );
* @param mixed $value The value to encode.
* @param int $flags Options to be passed to json_encode(). Default 0.
* @param int $depth Maximum depth to walk through $value. Must be greater than 0.
public function json_encode( $value, $flags = 0, $depth = 512 ) {
return wp_json_encode( $value, $flags, $depth );
* Test if a string ends with a string.
* @param string $haystack String to check.
* @param string $needle Suffix to check.
public function ends_with( $haystack, $needle ) {
return substr( $haystack, -strlen( $needle ) ) === $needle;
* Returns the site's blog_id in the WP.com ecosystem
public function get_blog_id_for_output() {
return $this->token_details['blog_id'];
* Returns the site's local blog_id.
* @param int $blog_id Blog ID.
public function get_blog_id( $blog_id ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
return $GLOBALS['blog_id'];
* Switch to blog and validate user.
* @param int $blog_id Blog ID.
* @param bool $verify_token_for_blog Whether to verify the token.
public function switch_to_blog_and_validate_user( $blog_id = 0, $verify_token_for_blog = true ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
if ( $this->is_restricted_blog( $blog_id ) ) {
return new WP_Error( 'unauthorized', 'User cannot access this restricted blog', 403 );
* If this is a private site we check for 2 things:
* 1. In case of user based authentication, we need to check if the logged-in user has the 'read' capability.
* 2. In case of site based authentication, make sure the endpoint accepts it.
if ( ( new Status() )->is_private_site() &&
! current_user_can( 'read' ) &&
! $this->endpoint->accepts_site_based_authentication()
return new WP_Error( 'unauthorized', 'User cannot access this private blog.', 403 );
* Switch to a user and blog based on the current request's Jetpack token when the endpoint accepts this feature.
protected function maybe_switch_to_token_user_and_site() {
if ( ! $this->endpoint->allow_jetpack_token_auth ) {
if ( ! class_exists( 'Jetpack_Server_Version' ) ) {
$token = Jetpack_Server_Version::get_token_from_authorization_header();
if ( ! $token || is_wp_error( $token ) ) {