[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/rest-api/ -> class-wp-rest-server.php (source)

   1  <?php
   2  /**
   3   * REST API: WP_REST_Server class
   4   *
   5   * @package WordPress
   6   * @subpackage REST_API
   7   * @since 4.4.0
   8   */
   9  
  10  /**
  11   * Core class used to implement the WordPress REST API server.
  12   *
  13   * @since 4.4.0
  14   */
  15  #[AllowDynamicProperties]
  16  class WP_REST_Server {
  17  
  18      /**
  19       * Alias for GET transport method.
  20       *
  21       * @since 4.4.0
  22       * @var string
  23       */
  24      const READABLE = 'GET';
  25  
  26      /**
  27       * Alias for POST transport method.
  28       *
  29       * @since 4.4.0
  30       * @var string
  31       */
  32      const CREATABLE = 'POST';
  33  
  34      /**
  35       * Alias for POST, PUT, PATCH transport methods together.
  36       *
  37       * @since 4.4.0
  38       * @var string
  39       */
  40      const EDITABLE = 'POST, PUT, PATCH';
  41  
  42      /**
  43       * Alias for DELETE transport method.
  44       *
  45       * @since 4.4.0
  46       * @var string
  47       */
  48      const DELETABLE = 'DELETE';
  49  
  50      /**
  51       * Alias for GET, POST, PUT, PATCH & DELETE transport methods together.
  52       *
  53       * @since 4.4.0
  54       * @var string
  55       */
  56      const ALLMETHODS = 'GET, POST, PUT, PATCH, DELETE';
  57  
  58      /**
  59       * Namespaces registered to the server.
  60       *
  61       * @since 4.4.0
  62       * @var array
  63       */
  64      protected $namespaces = array();
  65  
  66      /**
  67       * Endpoints registered to the server.
  68       *
  69       * @since 4.4.0
  70       * @var array
  71       */
  72      protected $endpoints = array();
  73  
  74      /**
  75       * Options defined for the routes.
  76       *
  77       * @since 4.4.0
  78       * @var array
  79       */
  80      protected $route_options = array();
  81  
  82      /**
  83       * Caches embedded requests.
  84       *
  85       * @since 5.4.0
  86       * @var array
  87       */
  88      protected $embed_cache = array();
  89  
  90      /**
  91       * Stores request objects that are currently being handled.
  92       *
  93       * @since 6.5.0
  94       * @var array
  95       */
  96      protected $dispatching_requests = array();
  97  
  98      /**
  99       * Instantiates the REST server.
 100       *
 101       * @since 4.4.0
 102       */
 103  	public function __construct() {
 104          $this->endpoints = array(
 105              // Meta endpoints.
 106              '/'         => array(
 107                  'callback' => array( $this, 'get_index' ),
 108                  'methods'  => 'GET',
 109                  'args'     => array(
 110                      'context' => array(
 111                          'default' => 'view',
 112                      ),
 113                  ),
 114              ),
 115              '/batch/v1' => array(
 116                  'callback' => array( $this, 'serve_batch_request_v1' ),
 117                  'methods'  => 'POST',
 118                  'args'     => array(
 119                      'validation' => array(
 120                          'type'    => 'string',
 121                          'enum'    => array( 'require-all-validate', 'normal' ),
 122                          'default' => 'normal',
 123                      ),
 124                      'requests'   => array(
 125                          'required' => true,
 126                          'type'     => 'array',
 127                          'maxItems' => $this->get_max_batch_size(),
 128                          'items'    => array(
 129                              'type'       => 'object',
 130                              'properties' => array(
 131                                  'method'  => array(
 132                                      'type'    => 'string',
 133                                      'enum'    => array( 'POST', 'PUT', 'PATCH', 'DELETE' ),
 134                                      'default' => 'POST',
 135                                  ),
 136                                  'path'    => array(
 137                                      'type'     => 'string',
 138                                      'required' => true,
 139                                  ),
 140                                  'body'    => array(
 141                                      'type'                 => 'object',
 142                                      'properties'           => array(),
 143                                      'additionalProperties' => true,
 144                                  ),
 145                                  'headers' => array(
 146                                      'type'                 => 'object',
 147                                      'properties'           => array(),
 148                                      'additionalProperties' => array(
 149                                          'type'  => array( 'string', 'array' ),
 150                                          'items' => array(
 151                                              'type' => 'string',
 152                                          ),
 153                                      ),
 154                                  ),
 155                              ),
 156                          ),
 157                      ),
 158                  ),
 159              ),
 160          );
 161      }
 162  
 163  
 164      /**
 165       * Checks the authentication headers if supplied.
 166       *
 167       * @since 4.4.0
 168       *
 169       * @return WP_Error|null|true WP_Error if authentication error occurred, null if authentication
 170       *                            method wasn't used, true if authentication succeeded.
 171       */
 172  	public function check_authentication() {
 173          /**
 174           * Filters REST API authentication errors.
 175           *
 176           * This is used to pass a WP_Error from an authentication method back to
 177           * the API.
 178           *
 179           * Authentication methods should check first if they're being used, as
 180           * multiple authentication methods can be enabled on a site (cookies,
 181           * HTTP basic auth, OAuth). If the authentication method hooked in is
 182           * not actually being attempted, null should be returned to indicate
 183           * another authentication method should check instead. Similarly,
 184           * callbacks should ensure the value is `null` before checking for
 185           * errors.
 186           *
 187           * A WP_Error instance can be returned if an error occurs, and this should
 188           * match the format used by API methods internally (that is, the `status`
 189           * data should be used). A callback can return `true` to indicate that
 190           * the authentication method was used, and it succeeded.
 191           *
 192           * @since 4.4.0
 193           *
 194           * @param WP_Error|null|true $errors WP_Error if authentication error occurred, null if authentication
 195           *                                   method wasn't used, true if authentication succeeded.
 196           */
 197          return apply_filters( 'rest_authentication_errors', null );
 198      }
 199  
 200      /**
 201       * Converts an error to a response object.
 202       *
 203       * This iterates over all error codes and messages to change it into a flat
 204       * array. This enables simpler client behavior, as it is represented as a
 205       * list in JSON rather than an object/map.
 206       *
 207       * @since 4.4.0
 208       * @since 5.7.0 Converted to a wrapper of {@see rest_convert_error_to_response()}.
 209       *
 210       * @param WP_Error $error WP_Error instance.
 211       * @return WP_REST_Response List of associative arrays with code and message keys.
 212       */
 213  	protected function error_to_response( $error ) {
 214          return rest_convert_error_to_response( $error );
 215      }
 216  
 217      /**
 218       * Retrieves an appropriate error representation in JSON.
 219       *
 220       * Note: This should only be used in WP_REST_Server::serve_request(), as it
 221       * cannot handle WP_Error internally. All callbacks and other internal methods
 222       * should instead return a WP_Error with the data set to an array that includes
 223       * a 'status' key, with the value being the HTTP status to send.
 224       *
 225       * @since 4.4.0
 226       *
 227       * @param string   $code    WP_Error-style code.
 228       * @param string   $message Human-readable message.
 229       * @param int|null $status  Optional. HTTP status code to send. Default null.
 230       * @return string JSON representation of the error.
 231       */
 232  	protected function json_error( $code, $message, $status = null ) {
 233          if ( $status ) {
 234              $this->set_status( $status );
 235          }
 236  
 237          $error = compact( 'code', 'message' );
 238  
 239          return wp_json_encode( $error );
 240      }
 241  
 242      /**
 243       * Gets the encoding options passed to {@see wp_json_encode}.
 244       *
 245       * @since 6.1.0
 246       *
 247       * @param \WP_REST_Request $request The current request object.
 248       *
 249       * @return int The JSON encode options.
 250       */
 251  	protected function get_json_encode_options( WP_REST_Request $request ) {
 252          $options = 0;
 253  
 254          if ( $request->has_param( '_pretty' ) ) {
 255              $options |= JSON_PRETTY_PRINT;
 256          }
 257  
 258          /**
 259           * Filters the JSON encoding options used to send the REST API response.
 260           *
 261           * @since 6.1.0
 262           *
 263           * @param int $options             JSON encoding options {@see json_encode()}.
 264           * @param WP_REST_Request $request Current request object.
 265           */
 266          return apply_filters( 'rest_json_encode_options', $options, $request );
 267      }
 268  
 269      /**
 270       * Handles serving a REST API request.
 271       *
 272       * Matches the current server URI to a route and runs the first matching
 273       * callback then outputs a JSON representation of the returned value.
 274       *
 275       * @since 4.4.0
 276       *
 277       * @see WP_REST_Server::dispatch()
 278       *
 279       * @global WP_User $current_user The currently authenticated user.
 280       *
 281       * @param string|null $path Optional. The request route. If not set, `$_SERVER['PATH_INFO']` will be used.
 282       *                          Default null.
 283       * @return null|false Null if not served and a HEAD request, false otherwise.
 284       */
 285  	public function serve_request( $path = null ) {
 286          /* @var WP_User|null $current_user */
 287          global $current_user;
 288  
 289          if ( $current_user instanceof WP_User && ! $current_user->exists() ) {
 290              /*
 291               * If there is no current user authenticated via other means, clear
 292               * the cached lack of user, so that an authenticate check can set it
 293               * properly.
 294               *
 295               * This is done because for authentications such as Application
 296               * Passwords, we don't want it to be accepted unless the current HTTP
 297               * request is a REST API request, which can't always be identified early
 298               * enough in evaluation.
 299               */
 300              $current_user = null;
 301          }
 302  
 303          /**
 304           * Filters whether JSONP is enabled for the REST API.
 305           *
 306           * @since 4.4.0
 307           *
 308           * @param bool $jsonp_enabled Whether JSONP is enabled. Default true.
 309           */
 310          $jsonp_enabled = apply_filters( 'rest_jsonp_enabled', true );
 311  
 312          $jsonp_callback = false;
 313          if ( isset( $_GET['_jsonp'] ) ) {
 314              $jsonp_callback = $_GET['_jsonp'];
 315          }
 316  
 317          $content_type = ( $jsonp_callback && $jsonp_enabled ) ? 'application/javascript' : 'application/json';
 318          $this->send_header( 'Content-Type', $content_type . '; charset=' . get_option( 'blog_charset' ) );
 319          $this->send_header( 'X-Robots-Tag', 'noindex' );
 320  
 321          $api_root = get_rest_url();
 322          if ( ! empty( $api_root ) ) {
 323              $this->send_header( 'Link', '<' . sanitize_url( $api_root ) . '>; rel="https://api.w.org/"' );
 324          }
 325  
 326          /*
 327           * Mitigate possible JSONP Flash attacks.
 328           *
 329           * https://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
 330           */
 331          $this->send_header( 'X-Content-Type-Options', 'nosniff' );
 332  
 333          /**
 334           * Filters whether the REST API is enabled.
 335           *
 336           * @since 4.4.0
 337           * @deprecated 4.7.0 Use the {@see 'rest_authentication_errors'} filter to
 338           *                   restrict access to the REST API.
 339           *
 340           * @param bool $rest_enabled Whether the REST API is enabled. Default true.
 341           */
 342          apply_filters_deprecated(
 343              'rest_enabled',
 344              array( true ),
 345              '4.7.0',
 346              'rest_authentication_errors',
 347              sprintf(
 348                  /* translators: %s: rest_authentication_errors */
 349                  __( 'The REST API can no longer be completely disabled, the %s filter can be used to restrict access to the API, instead.' ),
 350                  'rest_authentication_errors'
 351              )
 352          );
 353  
 354          if ( $jsonp_callback ) {
 355              if ( ! $jsonp_enabled ) {
 356                  echo $this->json_error( 'rest_callback_disabled', __( 'JSONP support is disabled on this site.' ), 400 );
 357                  return false;
 358              }
 359  
 360              if ( ! wp_check_jsonp_callback( $jsonp_callback ) ) {
 361                  echo $this->json_error( 'rest_callback_invalid', __( 'Invalid JSONP callback function.' ), 400 );
 362                  return false;
 363              }
 364          }
 365  
 366          if ( empty( $path ) ) {
 367              $path = $_SERVER['PATH_INFO'] ?? '/';
 368          }
 369  
 370          $request = new WP_REST_Request( $_SERVER['REQUEST_METHOD'], $path );
 371  
 372          $request->set_query_params( wp_unslash( $_GET ) );
 373          $request->set_body_params( wp_unslash( $_POST ) );
 374          $request->set_file_params( $_FILES );
 375          $request->set_headers( $this->get_headers( wp_unslash( $_SERVER ) ) );
 376          $request->set_body( self::get_raw_data() );
 377  
 378          /*
 379           * HTTP method override for clients that can't use PUT/PATCH/DELETE. First, we check
 380           * $_GET['_method']. If that is not set, we check for the HTTP_X_HTTP_METHOD_OVERRIDE
 381           * header.
 382           */
 383          $method_overridden = false;
 384          if ( isset( $_GET['_method'] ) ) {
 385              $request->set_method( $_GET['_method'] );
 386          } elseif ( isset( $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] ) ) {
 387              $request->set_method( $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] );
 388              $method_overridden = true;
 389          }
 390  
 391          $expose_headers = array( 'X-WP-Total', 'X-WP-TotalPages', 'Link' );
 392  
 393          /**
 394           * Filters the list of response headers that are exposed to REST API CORS requests.
 395           *
 396           * @since 5.5.0
 397           * @since 6.3.0 The `$request` parameter was added.
 398           *
 399           * @param string[]        $expose_headers The list of response headers to expose.
 400           * @param WP_REST_Request $request        The request in context.
 401           */
 402          $expose_headers = apply_filters( 'rest_exposed_cors_headers', $expose_headers, $request );
 403  
 404          $this->send_header( 'Access-Control-Expose-Headers', implode( ', ', $expose_headers ) );
 405  
 406          $allow_headers = array(
 407              'Authorization',
 408              'X-WP-Nonce',
 409              'Content-Disposition',
 410              'Content-MD5',
 411              'Content-Type',
 412          );
 413  
 414          /**
 415           * Filters the list of request headers that are allowed for REST API CORS requests.
 416           *
 417           * The allowed headers are passed to the browser to specify which
 418           * headers can be passed to the REST API. By default, we allow the
 419           * Content-* headers needed to upload files to the media endpoints.
 420           * As well as the Authorization and Nonce headers for allowing authentication.
 421           *
 422           * @since 5.5.0
 423           * @since 6.3.0 The `$request` parameter was added.
 424           *
 425           * @param string[]        $allow_headers The list of request headers to allow.
 426           * @param WP_REST_Request $request       The request in context.
 427           */
 428          $allow_headers = apply_filters( 'rest_allowed_cors_headers', $allow_headers, $request );
 429  
 430          $this->send_header( 'Access-Control-Allow-Headers', implode( ', ', $allow_headers ) );
 431  
 432          $result = $this->check_authentication();
 433  
 434          if ( ! is_wp_error( $result ) ) {
 435              $result = $this->dispatch( $request );
 436          }
 437  
 438          // Normalize to either WP_Error or WP_REST_Response...
 439          $result = rest_ensure_response( $result );
 440  
 441          // ...then convert WP_Error across.
 442          if ( is_wp_error( $result ) ) {
 443              $result = $this->error_to_response( $result );
 444          }
 445  
 446          /**
 447           * Filters the REST API response.
 448           *
 449           * Allows modification of the response before returning.
 450           *
 451           * @since 4.4.0
 452           * @since 4.5.0 Applied to embedded responses.
 453           *
 454           * @param WP_HTTP_Response $result  Result to send to the client. Usually a `WP_REST_Response`.
 455           * @param WP_REST_Server   $server  Server instance.
 456           * @param WP_REST_Request  $request Request used to generate the response.
 457           */
 458          $result = apply_filters( 'rest_post_dispatch', rest_ensure_response( $result ), $this, $request );
 459  
 460          // Wrap the response in an envelope if asked for.
 461          if ( isset( $_GET['_envelope'] ) ) {
 462              $embed  = isset( $_GET['_embed'] ) ? rest_parse_embed_param( $_GET['_embed'] ) : false;
 463              $result = $this->envelope_response( $result, $embed );
 464          }
 465  
 466          // Send extra data from response objects.
 467          $headers = $result->get_headers();
 468          $this->send_headers( $headers );
 469  
 470          $code = $result->get_status();
 471          $this->set_status( $code );
 472  
 473          /**
 474           * Filters whether to send no-cache headers on a REST API request.
 475           *
 476           * @since 4.4.0
 477           * @since 6.3.2 Moved the block to catch the filter added on rest_cookie_check_errors() from wp-includes/rest-api.php.
 478           *
 479           * @param bool $rest_send_nocache_headers Whether to send no-cache headers.
 480           */
 481          $send_no_cache_headers = apply_filters( 'rest_send_nocache_headers', is_user_logged_in() );
 482  
 483          /*
 484           * Send no-cache headers if $send_no_cache_headers is true,
 485           * OR if the HTTP_X_HTTP_METHOD_OVERRIDE is used but resulted a 4xx response code.
 486           */
 487          if ( $send_no_cache_headers || ( true === $method_overridden && str_starts_with( $code, '4' ) ) ) {
 488              foreach ( wp_get_nocache_headers() as $header => $header_value ) {
 489                  if ( empty( $header_value ) ) {
 490                      $this->remove_header( $header );
 491                  } else {
 492                      $this->send_header( $header, $header_value );
 493                  }
 494              }
 495          }
 496  
 497          /**
 498           * Filters whether the REST API request has already been served.
 499           *
 500           * Allow sending the request manually - by returning true, the API result
 501           * will not be sent to the client.
 502           *
 503           * @since 4.4.0
 504           *
 505           * @param bool             $served  Whether the request has already been served. Default false.
 506           * @param WP_HTTP_Response $result  Result to send to the client. Usually a `WP_REST_Response`.
 507           * @param WP_REST_Request  $request Request used to generate the response.
 508           * @param WP_REST_Server   $server  Server instance.
 509           */
 510          $served = apply_filters( 'rest_pre_serve_request', false, $result, $request, $this );
 511  
 512          if ( ! $served ) {
 513              if ( 'HEAD' === $request->get_method() ) {
 514                  return null;
 515              }
 516  
 517              // Embed links inside the request.
 518              $embed  = isset( $_GET['_embed'] ) ? rest_parse_embed_param( $_GET['_embed'] ) : false;
 519              $result = $this->response_to_data( $result, $embed );
 520  
 521              /**
 522               * Filters the REST API response.
 523               *
 524               * Allows modification of the response data after inserting
 525               * embedded data (if any) and before echoing the response data.
 526               *
 527               * @since 4.8.1
 528               *
 529               * @param array            $result  Response data to send to the client.
 530               * @param WP_REST_Server   $server  Server instance.
 531               * @param WP_REST_Request  $request Request used to generate the response.
 532               */
 533              $result = apply_filters( 'rest_pre_echo_response', $result, $this, $request );
 534  
 535              // The 204 response shouldn't have a body.
 536              if ( 204 === $code || null === $result ) {
 537                  return null;
 538              }
 539  
 540              $result = wp_json_encode( $result, $this->get_json_encode_options( $request ) );
 541  
 542              $json_error_message = $this->get_json_last_error();
 543  
 544              if ( $json_error_message ) {
 545                  $this->set_status( 500 );
 546                  $json_error_obj = new WP_Error(
 547                      'rest_encode_error',
 548                      $json_error_message,
 549                      array( 'status' => 500 )
 550                  );
 551  
 552                  $result = $this->error_to_response( $json_error_obj );
 553                  $result = wp_json_encode( $result->data, $this->get_json_encode_options( $request ) );
 554              }
 555  
 556              if ( $jsonp_callback ) {
 557                  // Prepend '/**/' to mitigate possible JSONP Flash attacks.
 558                  // https://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
 559                  echo '/**/' . $jsonp_callback . '(' . $result . ')';
 560              } else {
 561                  echo $result;
 562              }
 563          }
 564  
 565          return null;
 566      }
 567  
 568      /**
 569       * Converts a response to data to send.
 570       *
 571       * @since 4.4.0
 572       * @since 5.4.0 The `$embed` parameter can now contain a list of link relations to include.
 573       *
 574       * @param WP_REST_Response $response Response object.
 575       * @param bool|string[]    $embed    Whether to embed all links, a filtered list of link relations, or no links.
 576       * @return array {
 577       *     Data with sub-requests embedded.
 578       *
 579       *     @type array $_links    Links.
 580       *     @type array $_embedded Embedded objects.
 581       * }
 582       */
 583  	public function response_to_data( $response, $embed ) {
 584          $data  = $response->get_data();
 585          $links = self::get_compact_response_links( $response );
 586  
 587          if ( ! empty( $links ) ) {
 588              // Convert links to part of the data.
 589              $data['_links'] = $links;
 590          }
 591  
 592          if ( $embed ) {
 593              $this->embed_cache = array();
 594              // Determine if this is a numeric array.
 595              if ( wp_is_numeric_array( $data ) ) {
 596                  foreach ( $data as $key => $item ) {
 597                      $data[ $key ] = $this->embed_links( $item, $embed );
 598                  }
 599              } else {
 600                  $data = $this->embed_links( $data, $embed );
 601              }
 602              $this->embed_cache = array();
 603          }
 604  
 605          return $data;
 606      }
 607  
 608      /**
 609       * Retrieves links from a response.
 610       *
 611       * Extracts the links from a response into a structured hash, suitable for
 612       * direct output.
 613       *
 614       * @since 4.4.0
 615       *
 616       * @param WP_REST_Response $response Response to extract links from.
 617       * @return array Map of link relation to list of link hashes.
 618       */
 619  	public static function get_response_links( $response ) {
 620          $links = $response->get_links();
 621  
 622          if ( empty( $links ) ) {
 623              return array();
 624          }
 625  
 626          // Convert links to part of the data.
 627          $data = array();
 628          foreach ( $links as $rel => $items ) {
 629              $data[ $rel ] = array();
 630  
 631              foreach ( $items as $item ) {
 632                  $attributes         = $item['attributes'];
 633                  $attributes['href'] = $item['href'];
 634  
 635                  if ( 'self' !== $rel ) {
 636                      $data[ $rel ][] = $attributes;
 637                      continue;
 638                  }
 639  
 640                  $target_hints = self::get_target_hints_for_link( $attributes );
 641                  if ( $target_hints ) {
 642                      $attributes['targetHints'] = $target_hints;
 643                  }
 644  
 645                  $data[ $rel ][] = $attributes;
 646              }
 647          }
 648  
 649          return $data;
 650      }
 651  
 652      /**
 653       * Gets the target hints for a REST API Link.
 654       *
 655       * @since 6.7.0
 656       *
 657       * @param array $link The link to get target hints for.
 658       * @return array|null
 659       */
 660  	protected static function get_target_hints_for_link( $link ) {
 661          // Prefer targetHints that were specifically designated by the developer.
 662          if ( isset( $link['targetHints']['allow'] ) ) {
 663              return null;
 664          }
 665  
 666          $request = WP_REST_Request::from_url( $link['href'] );
 667          if ( ! $request ) {
 668              return null;
 669          }
 670  
 671          $server = rest_get_server();
 672          $match  = $server->match_request_to_handler( $request );
 673  
 674          if ( is_wp_error( $match ) ) {
 675              return null;
 676          }
 677  
 678          if ( is_wp_error( $request->has_valid_params() ) ) {
 679              return null;
 680          }
 681  
 682          if ( is_wp_error( $request->sanitize_params() ) ) {
 683              return null;
 684          }
 685  
 686          $target_hints = array();
 687  
 688          $response = new WP_REST_Response();
 689          $response->set_matched_route( $match[0] );
 690          $response->set_matched_handler( $match[1] );
 691          $headers = rest_send_allow_header( $response, $server, $request )->get_headers();
 692  
 693          foreach ( $headers as $name => $value ) {
 694              $name = WP_REST_Request::canonicalize_header_name( $name );
 695  
 696              $target_hints[ $name ] = array_map( 'trim', explode( ',', $value ) );
 697          }
 698  
 699          return $target_hints;
 700      }
 701  
 702      /**
 703       * Retrieves the CURIEs (compact URIs) used for relations.
 704       *
 705       * Extracts the links from a response into a structured hash, suitable for
 706       * direct output.
 707       *
 708       * @since 4.5.0
 709       *
 710       * @param WP_REST_Response $response Response to extract links from.
 711       * @return array Map of link relation to list of link hashes.
 712       */
 713  	public static function get_compact_response_links( $response ) {
 714          $links = self::get_response_links( $response );
 715  
 716          if ( empty( $links ) ) {
 717              return array();
 718          }
 719  
 720          $curies      = $response->get_curies();
 721          $used_curies = array();
 722  
 723          foreach ( $links as $rel => $items ) {
 724  
 725              // Convert $rel URIs to their compact versions if they exist.
 726              foreach ( $curies as $curie ) {
 727                  $href_prefix = substr( $curie['href'], 0, strpos( $curie['href'], '{rel}' ) );
 728                  if ( ! str_starts_with( $rel, $href_prefix ) ) {
 729                      continue;
 730                  }
 731  
 732                  // Relation now changes from '$uri' to '$curie:$relation'.
 733                  $rel_regex = str_replace( '\{rel\}', '(.+)', preg_quote( $curie['href'], '!' ) );
 734                  preg_match( '!' . $rel_regex . '!', $rel, $matches );
 735                  if ( $matches ) {
 736                      $new_rel                       = $curie['name'] . ':' . $matches[1];
 737                      $used_curies[ $curie['name'] ] = $curie;
 738                      $links[ $new_rel ]             = $items;
 739                      unset( $links[ $rel ] );
 740                      break;
 741                  }
 742              }
 743          }
 744  
 745          // Push the curies onto the start of the links array.
 746          if ( $used_curies ) {
 747              $links['curies'] = array_values( $used_curies );
 748          }
 749  
 750          return $links;
 751      }
 752  
 753      /**
 754       * Embeds the links from the data into the request.
 755       *
 756       * @since 4.4.0
 757       * @since 5.4.0 The `$embed` parameter can now contain a list of link relations to include.
 758       *
 759       * @param array         $data  Data from the request.
 760       * @param bool|string[] $embed Whether to embed all links or a filtered list of link relations.
 761       *                             Default true.
 762       * @return array {
 763       *     Data with sub-requests embedded.
 764       *
 765       *     @type array $_links    Links.
 766       *     @type array $_embedded Embedded objects.
 767       * }
 768       */
 769  	protected function embed_links( $data, $embed = true ) {
 770          if ( empty( $data['_links'] ) ) {
 771              return $data;
 772          }
 773  
 774          $embedded = array();
 775  
 776          foreach ( $data['_links'] as $rel => $links ) {
 777              /*
 778               * If a list of relations was specified, and the link relation
 779               * is not in the list of allowed relations, don't process the link.
 780               */
 781              if ( is_array( $embed ) && ! in_array( $rel, $embed, true ) ) {
 782                  continue;
 783              }
 784  
 785              $embeds = array();
 786  
 787              foreach ( $links as $item ) {
 788                  // Determine if the link is embeddable.
 789                  if ( empty( $item['embeddable'] ) ) {
 790                      // Ensure we keep the same order.
 791                      $embeds[] = array();
 792                      continue;
 793                  }
 794  
 795                  if ( ! array_key_exists( $item['href'], $this->embed_cache ) ) {
 796                      // Run through our internal routing and serve.
 797                      $request = WP_REST_Request::from_url( $item['href'] );
 798                      if ( ! $request ) {
 799                          $embeds[] = array();
 800                          continue;
 801                      }
 802  
 803                      // Embedded resources get passed context=embed.
 804                      if ( empty( $request['context'] ) ) {
 805                          $request['context'] = 'embed';
 806                      }
 807  
 808                      if ( empty( $request['per_page'] ) ) {
 809                          $matched = $this->match_request_to_handler( $request );
 810                          if ( ! is_wp_error( $matched ) && isset( $matched[1]['args']['per_page']['maximum'] ) ) {
 811                              $request['per_page'] = (int) $matched[1]['args']['per_page']['maximum'];
 812                          }
 813                      }
 814  
 815                      $response = $this->dispatch( $request );
 816  
 817                      /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
 818                      $response = apply_filters( 'rest_post_dispatch', rest_ensure_response( $response ), $this, $request );
 819  
 820                      $this->embed_cache[ $item['href'] ] = $this->response_to_data( $response, false );
 821                  }
 822  
 823                  $embeds[] = $this->embed_cache[ $item['href'] ];
 824              }
 825  
 826              // Determine if any real links were found.
 827              $has_links = count( array_filter( $embeds ) );
 828  
 829              if ( $has_links ) {
 830                  $embedded[ $rel ] = $embeds;
 831              }
 832          }
 833  
 834          if ( ! empty( $embedded ) ) {
 835              $data['_embedded'] = $embedded;
 836          }
 837  
 838          return $data;
 839      }
 840  
 841      /**
 842       * Wraps the response in an envelope.
 843       *
 844       * The enveloping technique is used to work around browser/client
 845       * compatibility issues. Essentially, it converts the full HTTP response to
 846       * data instead.
 847       *
 848       * @since 4.4.0
 849       * @since 6.0.0 The `$embed` parameter can now contain a list of link relations to include.
 850       *
 851       * @param WP_REST_Response $response Response object.
 852       * @param bool|string[]    $embed    Whether to embed all links, a filtered list of link relations, or no links.
 853       * @return WP_REST_Response New response with wrapped data
 854       */
 855  	public function envelope_response( $response, $embed ) {
 856          $envelope = array(
 857              'body'    => $this->response_to_data( $response, $embed ),
 858              'status'  => $response->get_status(),
 859              'headers' => $response->get_headers(),
 860          );
 861  
 862          /**
 863           * Filters the enveloped form of a REST API response.
 864           *
 865           * @since 4.4.0
 866           *
 867           * @param array            $envelope {
 868           *     Envelope data.
 869           *
 870           *     @type array $body    Response data.
 871           *     @type int   $status  The 3-digit HTTP status code.
 872           *     @type array $headers Map of header name to header value.
 873           * }
 874           * @param WP_REST_Response $response Original response data.
 875           */
 876          $envelope = apply_filters( 'rest_envelope_response', $envelope, $response );
 877  
 878          // Ensure it's still a response and return.
 879          return rest_ensure_response( $envelope );
 880      }
 881  
 882      /**
 883       * Registers a route to the server.
 884       *
 885       * @since 4.4.0
 886       *
 887       * @param string $route_namespace Namespace.
 888       * @param string $route           The REST route.
 889       * @param array  $route_args      Route arguments.
 890       * @param bool   $override        Optional. Whether the route should be overridden if it already exists.
 891       *                                Default false.
 892       */
 893  	public function register_route( $route_namespace, $route, $route_args, $override = false ) {
 894          if ( ! isset( $this->namespaces[ $route_namespace ] ) ) {
 895              $this->namespaces[ $route_namespace ] = array();
 896  
 897              $this->register_route(
 898                  $route_namespace,
 899                  '/' . $route_namespace,
 900                  array(
 901                      array(
 902                          'methods'  => self::READABLE,
 903                          'callback' => array( $this, 'get_namespace_index' ),
 904                          'args'     => array(
 905                              'namespace' => array(
 906                                  'default' => $route_namespace,
 907                              ),
 908                              'context'   => array(
 909                                  'default' => 'view',
 910                              ),
 911                          ),
 912                      ),
 913                  )
 914              );
 915          }
 916  
 917          // Associative to avoid double-registration.
 918          $this->namespaces[ $route_namespace ][ $route ] = true;
 919  
 920          $route_args['namespace'] = $route_namespace;
 921  
 922          if ( $override || empty( $this->endpoints[ $route ] ) ) {
 923              $this->endpoints[ $route ] = $route_args;
 924          } else {
 925              $this->endpoints[ $route ] = array_merge( $this->endpoints[ $route ], $route_args );
 926          }
 927      }
 928  
 929      /**
 930       * Retrieves the route map.
 931       *
 932       * The route map is an associative array with path regexes as the keys. The
 933       * value is an indexed array with the callback function/method as the first
 934       * item, and a bitmask of HTTP methods as the second item (see the class
 935       * constants).
 936       *
 937       * Each route can be mapped to more than one callback by using an array of
 938       * the indexed arrays. This allows mapping e.g. GET requests to one callback
 939       * and POST requests to another.
 940       *
 941       * Note that the path regexes (array keys) must have @ escaped, as this is
 942       * used as the delimiter with preg_match()
 943       *
 944       * @since 4.4.0
 945       * @since 5.4.0 Added `$route_namespace` parameter.
 946       *
 947       * @param string $route_namespace Optionally, only return routes in the given namespace.
 948       * @return array `'/path/regex' => array( $callback, $bitmask )` or
 949       *               `'/path/regex' => array( array( $callback, $bitmask ), ...)`.
 950       */
 951  	public function get_routes( $route_namespace = '' ) {
 952          $endpoints = $this->endpoints;
 953  
 954          if ( $route_namespace ) {
 955              $endpoints = wp_list_filter( $endpoints, array( 'namespace' => $route_namespace ) );
 956          }
 957  
 958          /**
 959           * Filters the array of available REST API endpoints.
 960           *
 961           * @since 4.4.0
 962           *
 963           * @param array $endpoints The available endpoints. An array of matching regex patterns, each mapped
 964           *                         to an array of callbacks for the endpoint. These take the format
 965           *                         `'/path/regex' => array( $callback, $bitmask )` or
 966           *                         `'/path/regex' => array( array( $callback, $bitmask ).
 967           */
 968          $endpoints = apply_filters( 'rest_endpoints', $endpoints );
 969  
 970          // Normalize the endpoints.
 971          $defaults = array(
 972              'methods'       => '',
 973              'accept_json'   => false,
 974              'accept_raw'    => false,
 975              'show_in_index' => true,
 976              'args'          => array(),
 977          );
 978  
 979          foreach ( $endpoints as $route => &$handlers ) {
 980  
 981              if ( isset( $handlers['callback'] ) ) {
 982                  // Single endpoint, add one deeper.
 983                  $handlers = array( $handlers );
 984              }
 985  
 986              if ( ! isset( $this->route_options[ $route ] ) ) {
 987                  $this->route_options[ $route ] = array();
 988              }
 989  
 990              foreach ( $handlers as $key => &$handler ) {
 991  
 992                  if ( ! is_numeric( $key ) ) {
 993                      // Route option, move it to the options.
 994                      $this->route_options[ $route ][ $key ] = $handler;
 995                      unset( $handlers[ $key ] );
 996                      continue;
 997                  }
 998  
 999                  $handler = wp_parse_args( $handler, $defaults );
1000  
1001                  // Allow comma-separated HTTP methods.
1002                  if ( is_string( $handler['methods'] ) ) {
1003                      $methods = explode( ',', $handler['methods'] );
1004                  } elseif ( is_array( $handler['methods'] ) ) {
1005                      $methods = $handler['methods'];
1006                  } else {
1007                      $methods = array();
1008                  }
1009  
1010                  $handler['methods'] = array();
1011  
1012                  foreach ( $methods as $method ) {
1013                      $method                        = strtoupper( trim( $method ) );
1014                      $handler['methods'][ $method ] = true;
1015                  }
1016              }
1017          }
1018  
1019          return $endpoints;
1020      }
1021  
1022      /**
1023       * Retrieves namespaces registered on the server.
1024       *
1025       * @since 4.4.0
1026       *
1027       * @return string[] List of registered namespaces.
1028       */
1029  	public function get_namespaces() {
1030          return array_keys( $this->namespaces );
1031      }
1032  
1033      /**
1034       * Retrieves specified options for a route.
1035       *
1036       * @since 4.4.0
1037       *
1038       * @param string $route Route pattern to fetch options for.
1039       * @return array|null Data as an associative array if found, or null if not found.
1040       */
1041  	public function get_route_options( $route ) {
1042          if ( ! isset( $this->route_options[ $route ] ) ) {
1043              return null;
1044          }
1045  
1046          return $this->route_options[ $route ];
1047      }
1048  
1049      /**
1050       * Matches the request to a callback and call it.
1051       *
1052       * @since 4.4.0
1053       *
1054       * @param WP_REST_Request $request Request to attempt dispatching.
1055       * @return WP_REST_Response Response returned by the callback.
1056       */
1057  	public function dispatch( $request ) {
1058          $this->dispatching_requests[] = $request;
1059  
1060          /**
1061           * Filters the pre-calculated result of a REST API dispatch request.
1062           *
1063           * Allow hijacking the request before dispatching by returning a non-empty. The returned value
1064           * will be used to serve the request instead.
1065           *
1066           * @since 4.4.0
1067           *
1068           * @param mixed           $result  Response to replace the requested version with. Can be anything
1069           *                                 a normal endpoint can return, or null to not hijack the request.
1070           * @param WP_REST_Server  $server  Server instance.
1071           * @param WP_REST_Request $request Request used to generate the response.
1072           */
1073          $result = apply_filters( 'rest_pre_dispatch', null, $this, $request );
1074  
1075          if ( ! empty( $result ) ) {
1076  
1077              // Normalize to either WP_Error or WP_REST_Response...
1078              $result = rest_ensure_response( $result );
1079  
1080              // ...then convert WP_Error across.
1081              if ( is_wp_error( $result ) ) {
1082                  $result = $this->error_to_response( $result );
1083              }
1084  
1085              array_pop( $this->dispatching_requests );
1086              return $result;
1087          }
1088  
1089          $error   = null;
1090          $matched = $this->match_request_to_handler( $request );
1091  
1092          if ( is_wp_error( $matched ) ) {
1093              $response = $this->error_to_response( $matched );
1094              array_pop( $this->dispatching_requests );
1095              return $response;
1096          }
1097  
1098          list( $route, $handler ) = $matched;
1099  
1100          if ( ! is_callable( $handler['callback'] ) ) {
1101              $error = new WP_Error(
1102                  'rest_invalid_handler',
1103                  __( 'The handler for the route is invalid.' ),
1104                  array( 'status' => 500 )
1105              );
1106          }
1107  
1108          if ( ! is_wp_error( $error ) ) {
1109              $check_required = $request->has_valid_params();
1110              if ( is_wp_error( $check_required ) ) {
1111                  $error = $check_required;
1112              } else {
1113                  $check_sanitized = $request->sanitize_params();
1114                  if ( is_wp_error( $check_sanitized ) ) {
1115                      $error = $check_sanitized;
1116                  }
1117              }
1118          }
1119  
1120          $response = $this->respond_to_request( $request, $route, $handler, $error );
1121          array_pop( $this->dispatching_requests );
1122          return $response;
1123      }
1124  
1125      /**
1126       * Returns whether the REST server is currently dispatching / responding to a request.
1127       *
1128       * This may be a standalone REST API request, or an internal request dispatched from within a regular page load.
1129       *
1130       * @since 6.5.0
1131       *
1132       * @return bool Whether the REST server is currently handling a request.
1133       */
1134  	public function is_dispatching() {
1135          return (bool) $this->dispatching_requests;
1136      }
1137  
1138      /**
1139       * Matches a request object to its handler.
1140       *
1141       * @access private
1142       * @since 5.6.0
1143       *
1144       * @param WP_REST_Request $request The request object.
1145       * @return array|WP_Error The route and request handler on success or a WP_Error instance if no handler was found.
1146       */
1147  	protected function match_request_to_handler( $request ) {
1148          $method = $request->get_method();
1149          $path   = $request->get_route();
1150  
1151          $with_namespace = array();
1152  
1153          foreach ( $this->get_namespaces() as $namespace ) {
1154              if ( str_starts_with( trailingslashit( ltrim( $path, '/' ) ), $namespace ) ) {
1155                  $with_namespace[] = $this->get_routes( $namespace );
1156              }
1157          }
1158  
1159          if ( $with_namespace ) {
1160              $routes = array_merge( ...$with_namespace );
1161          } else {
1162              $routes = $this->get_routes();
1163          }
1164  
1165          foreach ( $routes as $route => $handlers ) {
1166              $match = preg_match( '@^' . $route . '$@i', $path, $matches );
1167  
1168              if ( ! $match ) {
1169                  continue;
1170              }
1171  
1172              $args = array();
1173  
1174              foreach ( $matches as $param => $value ) {
1175                  if ( ! is_int( $param ) ) {
1176                      $args[ $param ] = $value;
1177                  }
1178              }
1179  
1180              foreach ( $handlers as $handler ) {
1181                  $callback = $handler['callback'];
1182  
1183                  // Fallback to GET method if no HEAD method is registered.
1184                  $checked_method = $method;
1185                  if ( 'HEAD' === $method && empty( $handler['methods']['HEAD'] ) ) {
1186                      $checked_method = 'GET';
1187                  }
1188                  if ( empty( $handler['methods'][ $checked_method ] ) ) {
1189                      continue;
1190                  }
1191  
1192                  if ( ! is_callable( $callback ) ) {
1193                      return array( $route, $handler );
1194                  }
1195  
1196                  $request->set_url_params( $args );
1197                  $request->set_attributes( $handler );
1198  
1199                  $defaults = array();
1200  
1201                  foreach ( $handler['args'] as $arg => $options ) {
1202                      if ( isset( $options['default'] ) ) {
1203                          $defaults[ $arg ] = $options['default'];
1204                      }
1205                  }
1206  
1207                  $request->set_default_params( $defaults );
1208  
1209                  return array( $route, $handler );
1210              }
1211          }
1212  
1213          return new WP_Error(
1214              'rest_no_route',
1215              __( 'No route was found matching the URL and request method.' ),
1216              array( 'status' => 404 )
1217          );
1218      }
1219  
1220      /**
1221       * Dispatches the request to the callback handler.
1222       *
1223       * @access private
1224       * @since 5.6.0
1225       *
1226       * @param WP_REST_Request $request  The request object.
1227       * @param string          $route    The matched route regex.
1228       * @param array           $handler  The matched route handler.
1229       * @param WP_Error|null   $response The current error object if any.
1230       * @return WP_REST_Response
1231       */
1232  	protected function respond_to_request( $request, $route, $handler, $response ) {
1233          /**
1234           * Filters the response before executing any REST API callbacks.
1235           *
1236           * Allows plugins to perform additional validation after a
1237           * request is initialized and matched to a registered route,
1238           * but before it is executed.
1239           *
1240           * Note that this filter will not be called for requests that
1241           * fail to authenticate or match to a registered route.
1242           *
1243           * @since 4.7.0
1244           *
1245           * @param WP_REST_Response|WP_HTTP_Response|WP_Error|mixed $response Result to send to the client.
1246           *                                                                   Usually a WP_REST_Response or WP_Error.
1247           * @param array                                            $handler  Route handler used for the request.
1248           * @param WP_REST_Request                                  $request  Request used to generate the response.
1249           */
1250          $response = apply_filters( 'rest_request_before_callbacks', $response, $handler, $request );
1251  
1252          // Check permission specified on the route.
1253          if ( ! is_wp_error( $response ) && ! empty( $handler['permission_callback'] ) ) {
1254              $permission = call_user_func( $handler['permission_callback'], $request );
1255  
1256              if ( is_wp_error( $permission ) ) {
1257                  $response = $permission;
1258              } elseif ( false === $permission || null === $permission ) {
1259                  $response = new WP_Error(
1260                      'rest_forbidden',
1261                      __( 'Sorry, you are not allowed to do that.' ),
1262                      array( 'status' => rest_authorization_required_code() )
1263                  );
1264              }
1265          }
1266  
1267          if ( ! is_wp_error( $response ) ) {
1268              /**
1269               * Filters the REST API dispatch request result.
1270               *
1271               * Allow plugins to override dispatching the request.
1272               *
1273               * @since 4.4.0
1274               * @since 4.5.0 Added `$route` and `$handler` parameters.
1275               *
1276               * @param mixed           $dispatch_result Dispatch result, will be used if not empty.
1277               * @param WP_REST_Request $request         Request used to generate the response.
1278               * @param string          $route           Route matched for the request.
1279               * @param array           $handler         Route handler used for the request.
1280               */
1281              $dispatch_result = apply_filters( 'rest_dispatch_request', null, $request, $route, $handler );
1282  
1283              // Allow plugins to halt the request via this filter.
1284              if ( null !== $dispatch_result ) {
1285                  $response = $dispatch_result;
1286              } else {
1287                  $response = call_user_func( $handler['callback'], $request );
1288              }
1289          }
1290  
1291          /**
1292           * Filters the response immediately after executing any REST API
1293           * callbacks.
1294           *
1295           * Allows plugins to perform any needed cleanup, for example,
1296           * to undo changes made during the {@see 'rest_request_before_callbacks'}
1297           * filter.
1298           *
1299           * Note that this filter will not be called for requests that
1300           * fail to authenticate or match to a registered route.
1301           *
1302           * Note that an endpoint's `permission_callback` can still be
1303           * called after this filter - see `rest_send_allow_header()`.
1304           *
1305           * @since 4.7.0
1306           *
1307           * @param WP_REST_Response|WP_HTTP_Response|WP_Error|mixed $response Result to send to the client.
1308           *                                                                   Usually a WP_REST_Response or WP_Error.
1309           * @param array                                            $handler  Route handler used for the request.
1310           * @param WP_REST_Request                                  $request  Request used to generate the response.
1311           */
1312          $response = apply_filters( 'rest_request_after_callbacks', $response, $handler, $request );
1313  
1314          if ( is_wp_error( $response ) ) {
1315              $response = $this->error_to_response( $response );
1316          } else {
1317              $response = rest_ensure_response( $response );
1318          }
1319  
1320          $response->set_matched_route( $route );
1321          $response->set_matched_handler( $handler );
1322  
1323          return $response;
1324      }
1325  
1326      /**
1327       * Returns if an error occurred during most recent JSON encode/decode.
1328       *
1329       * Strings to be translated will be in format like
1330       * "Encoding error: Maximum stack depth exceeded".
1331       *
1332       * @since 4.4.0
1333       *
1334       * @return false|string Boolean false or string error message.
1335       */
1336  	protected function get_json_last_error() {
1337          if ( JSON_ERROR_NONE === json_last_error() ) {
1338              return false;
1339          }
1340  
1341          return json_last_error_msg();
1342      }
1343  
1344      /**
1345       * Retrieves the site index.
1346       *
1347       * This endpoint describes the capabilities of the site.
1348       *
1349       * @since 4.4.0
1350       *
1351       * @param WP_REST_Request $request Request data.
1352       * @return WP_REST_Response The API root index data.
1353       */
1354  	public function get_index( $request ) {
1355          // General site data.
1356          $available = array(
1357              'name'            => get_option( 'blogname' ),
1358              'description'     => get_option( 'blogdescription' ),
1359              'url'             => get_option( 'siteurl' ),
1360              'home'            => home_url(),
1361              'gmt_offset'      => get_option( 'gmt_offset' ),
1362              'timezone_string' => get_option( 'timezone_string' ),
1363              'page_for_posts'  => (int) get_option( 'page_for_posts' ),
1364              'page_on_front'   => (int) get_option( 'page_on_front' ),
1365              'show_on_front'   => get_option( 'show_on_front' ),
1366              'namespaces'      => array_keys( $this->namespaces ),
1367              'authentication'  => array(),
1368              'routes'          => $this->get_data_for_routes( $this->get_routes(), $request['context'] ),
1369          );
1370  
1371          // Add media processing settings for users who can upload files.
1372          if ( wp_is_client_side_media_processing_enabled() && current_user_can( 'upload_files' ) ) {
1373              // Image sizes keyed by name for client-side media processing.
1374              $available['image_sizes'] = array();
1375              foreach ( wp_get_registered_image_subsizes() as $name => $size ) {
1376                  $available['image_sizes'][ $name ] = $size;
1377              }
1378  
1379              /** This filter is documented in wp-admin/includes/image.php */
1380              $available['image_size_threshold'] = (int) apply_filters( 'big_image_size_threshold', 2560, array( 0, 0 ), '', 0 );
1381          }
1382  
1383          $response = new WP_REST_Response( $available );
1384  
1385          $fields = $request['_fields'] ?? '';
1386          $fields = wp_parse_list( $fields );
1387          if ( empty( $fields ) ) {
1388              $fields[] = '_links';
1389          }
1390  
1391          if ( $request->has_param( '_embed' ) ) {
1392              $fields[] = '_embedded';
1393          }
1394  
1395          if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) {
1396              $response->add_link( 'help', 'https://developer.wordpress.org/rest-api/' );
1397              $this->add_active_theme_link_to_index( $response );
1398              $this->add_site_logo_to_index( $response );
1399              $this->add_site_icon_to_index( $response );
1400          } else {
1401              if ( rest_is_field_included( 'site_logo', $fields ) ) {
1402                  $this->add_site_logo_to_index( $response );
1403              }
1404              if ( rest_is_field_included( 'site_icon', $fields ) || rest_is_field_included( 'site_icon_url', $fields ) ) {
1405                  $this->add_site_icon_to_index( $response );
1406              }
1407          }
1408  
1409          /**
1410           * Filters the REST API root index data.
1411           *
1412           * This contains the data describing the API. This includes information
1413           * about supported authentication schemes, supported namespaces, routes
1414           * available on the API, and a small amount of data about the site.
1415           *
1416           * @since 4.4.0
1417           * @since 6.0.0 Added `$request` parameter.
1418           *
1419           * @param WP_REST_Response $response Response data.
1420           * @param WP_REST_Request  $request  Request data.
1421           */
1422          return apply_filters( 'rest_index', $response, $request );
1423      }
1424  
1425      /**
1426       * Adds a link to the active theme for users who have proper permissions.
1427       *
1428       * @since 5.7.0
1429       *
1430       * @param WP_REST_Response $response REST API response.
1431       */
1432  	protected function add_active_theme_link_to_index( WP_REST_Response $response ) {
1433          $should_add = current_user_can( 'switch_themes' ) || current_user_can( 'manage_network_themes' );
1434  
1435          if ( ! $should_add && current_user_can( 'edit_posts' ) ) {
1436              $should_add = true;
1437          }
1438  
1439          if ( ! $should_add ) {
1440              foreach ( get_post_types( array( 'show_in_rest' => true ), 'objects' ) as $post_type ) {
1441                  if ( current_user_can( $post_type->cap->edit_posts ) ) {
1442                      $should_add = true;
1443                      break;
1444                  }
1445              }
1446          }
1447  
1448          if ( $should_add ) {
1449              $theme = wp_get_theme();
1450              $response->add_link( 'https://api.w.org/active-theme', rest_url( 'wp/v2/themes/' . $theme->get_stylesheet() ) );
1451          }
1452      }
1453  
1454      /**
1455       * Exposes the site logo through the WordPress REST API.
1456       *
1457       * This is used for fetching this information when user has no rights
1458       * to update settings.
1459       *
1460       * @since 5.8.0
1461       *
1462       * @param WP_REST_Response $response REST API response.
1463       */
1464  	protected function add_site_logo_to_index( WP_REST_Response $response ) {
1465          $site_logo_id = get_theme_mod( 'custom_logo', 0 );
1466  
1467          $this->add_image_to_index( $response, $site_logo_id, 'site_logo' );
1468      }
1469  
1470      /**
1471       * Exposes the site icon through the WordPress REST API.
1472       *
1473       * This is used for fetching this information when user has no rights
1474       * to update settings.
1475       *
1476       * @since 5.9.0
1477       *
1478       * @param WP_REST_Response $response REST API response.
1479       */
1480  	protected function add_site_icon_to_index( WP_REST_Response $response ) {
1481          $site_icon_id = get_option( 'site_icon', 0 );
1482  
1483          $this->add_image_to_index( $response, $site_icon_id, 'site_icon' );
1484  
1485          $response->data['site_icon_url'] = get_site_icon_url();
1486      }
1487  
1488      /**
1489       * Exposes an image through the WordPress REST API.
1490       * This is used for fetching this information when user has no rights
1491       * to update settings.
1492       *
1493       * @since 5.9.0
1494       *
1495       * @param WP_REST_Response $response REST API response.
1496       * @param int              $image_id Image attachment ID.
1497       * @param string           $type     Type of Image.
1498       */
1499  	protected function add_image_to_index( WP_REST_Response $response, $image_id, $type ) {
1500          $response->data[ $type ] = (int) $image_id;
1501          if ( $image_id ) {
1502              $response->add_link(
1503                  'https://api.w.org/featuredmedia',
1504                  rest_url( rest_get_route_for_post( $image_id ) ),
1505                  array(
1506                      'embeddable' => true,
1507                      'type'       => $type,
1508                  )
1509              );
1510          }
1511      }
1512  
1513      /**
1514       * Retrieves the index for a namespace.
1515       *
1516       * @since 4.4.0
1517       *
1518       * @param WP_REST_Request $request REST request instance.
1519       * @return WP_REST_Response|WP_Error WP_REST_Response instance if the index was found,
1520       *                                   WP_Error if the namespace isn't set.
1521       */
1522  	public function get_namespace_index( $request ) {
1523          $namespace = $request['namespace'];
1524  
1525          if ( ! isset( $this->namespaces[ $namespace ] ) ) {
1526              return new WP_Error(
1527                  'rest_invalid_namespace',
1528                  __( 'The specified namespace could not be found.' ),
1529                  array( 'status' => 404 )
1530              );
1531          }
1532  
1533          $routes    = $this->namespaces[ $namespace ];
1534          $endpoints = array_intersect_key( $this->get_routes(), $routes );
1535  
1536          $data     = array(
1537              'namespace' => $namespace,
1538              'routes'    => $this->get_data_for_routes( $endpoints, $request['context'] ),
1539          );
1540          $response = rest_ensure_response( $data );
1541  
1542          // Link to the root index.
1543          $response->add_link( 'up', rest_url( '/' ) );
1544  
1545          /**
1546           * Filters the REST API namespace index data.
1547           *
1548           * This typically is just the route data for the namespace, but you can
1549           * add any data you'd like here.
1550           *
1551           * @since 4.4.0
1552           *
1553           * @param WP_REST_Response $response Response data.
1554           * @param WP_REST_Request  $request  Request data. The namespace is passed as the 'namespace' parameter.
1555           */
1556          return apply_filters( 'rest_namespace_index', $response, $request );
1557      }
1558  
1559      /**
1560       * Retrieves the publicly-visible data for routes.
1561       *
1562       * @since 4.4.0
1563       *
1564       * @param array  $routes  Routes to get data for.
1565       * @param string $context Optional. Context for data. Accepts 'view' or 'help'. Default 'view'.
1566       * @return array[] Route data to expose in indexes, keyed by route.
1567       */
1568  	public function get_data_for_routes( $routes, $context = 'view' ) {
1569          $available = array();
1570  
1571          // Find the available routes.
1572          foreach ( $routes as $route => $callbacks ) {
1573              $data = $this->get_data_for_route( $route, $callbacks, $context );
1574              if ( empty( $data ) ) {
1575                  continue;
1576              }
1577  
1578              /**
1579               * Filters the publicly-visible data for a single REST API route.
1580               *
1581               * @since 4.4.0
1582               *
1583               * @param array $data Publicly-visible data for the route.
1584               */
1585              $available[ $route ] = apply_filters( 'rest_endpoints_description', $data );
1586          }
1587  
1588          /**
1589           * Filters the publicly-visible data for REST API routes.
1590           *
1591           * This data is exposed on indexes and can be used by clients or
1592           * developers to investigate the site and find out how to use it. It
1593           * acts as a form of self-documentation.
1594           *
1595           * @since 4.4.0
1596           *
1597           * @param array[] $available Route data to expose in indexes, keyed by route.
1598           * @param array   $routes    Internal route data as an associative array.
1599           */
1600          return apply_filters( 'rest_route_data', $available, $routes );
1601      }
1602  
1603      /**
1604       * Retrieves publicly-visible data for the route.
1605       *
1606       * @since 4.4.0
1607       *
1608       * @param string $route     Route to get data for.
1609       * @param array  $callbacks Callbacks to convert to data.
1610       * @param string $context   Optional. Context for the data. Accepts 'view' or 'help'. Default 'view'.
1611       * @return array|null Data for the route, or null if no publicly-visible data.
1612       */
1613  	public function get_data_for_route( $route, $callbacks, $context = 'view' ) {
1614          $data = array(
1615              'namespace' => '',
1616              'methods'   => array(),
1617              'endpoints' => array(),
1618          );
1619  
1620          $allow_batch = false;
1621  
1622          if ( isset( $this->route_options[ $route ] ) ) {
1623              $options = $this->route_options[ $route ];
1624  
1625              if ( isset( $options['namespace'] ) ) {
1626                  $data['namespace'] = $options['namespace'];
1627              }
1628  
1629              $allow_batch = $options['allow_batch'] ?? false;
1630  
1631              if ( isset( $options['schema'] ) && 'help' === $context ) {
1632                  $data['schema'] = call_user_func( $options['schema'] );
1633              }
1634          }
1635  
1636          $allowed_schema_keywords = array_flip( wp_get_json_schema_allowed_keywords( 'rest-api' ) );
1637  
1638          $route = preg_replace( '#\(\?P<(\w+?)>.*?\)#', '{$1}', $route );
1639  
1640          foreach ( $callbacks as $callback ) {
1641              // Skip to the next route if any callback is hidden.
1642              if ( empty( $callback['show_in_index'] ) ) {
1643                  continue;
1644              }
1645  
1646              $data['methods'] = array_merge( $data['methods'], array_keys( $callback['methods'] ) );
1647              $endpoint_data   = array(
1648                  'methods' => array_keys( $callback['methods'] ),
1649              );
1650  
1651              $callback_batch = $callback['allow_batch'] ?? $allow_batch;
1652  
1653              if ( $callback_batch ) {
1654                  $endpoint_data['allow_batch'] = $callback_batch;
1655              }
1656  
1657              if ( isset( $callback['args'] ) ) {
1658                  $endpoint_data['args'] = array();
1659  
1660                  foreach ( $callback['args'] as $key => $opts ) {
1661                      if ( is_string( $opts ) ) {
1662                          $opts = array( $opts => 0 );
1663                      } elseif ( ! is_array( $opts ) ) {
1664                          $opts = array();
1665                      }
1666                      $arg_data             = array_intersect_key( $opts, $allowed_schema_keywords );
1667                      $arg_data['required'] = ! empty( $opts['required'] );
1668  
1669                      $endpoint_data['args'][ $key ] = $arg_data;
1670                  }
1671              }
1672  
1673              $data['endpoints'][] = $endpoint_data;
1674  
1675              // For non-variable routes, generate links.
1676              if ( ! str_contains( $route, '{' ) ) {
1677                  $data['_links'] = array(
1678                      'self' => array(
1679                          array(
1680                              'href' => rest_url( $route ),
1681                          ),
1682                      ),
1683                  );
1684              }
1685          }
1686  
1687          if ( empty( $data['methods'] ) ) {
1688              // No methods supported, hide the route.
1689              return null;
1690          }
1691  
1692          return $data;
1693      }
1694  
1695      /**
1696       * Gets the maximum number of requests that can be included in a batch.
1697       *
1698       * @since 5.6.0
1699       *
1700       * @return int The maximum requests.
1701       */
1702  	protected function get_max_batch_size() {
1703          /**
1704           * Filters the maximum number of REST API requests that can be included in a batch.
1705           *
1706           * @since 5.6.0
1707           *
1708           * @param int $max_size The maximum size.
1709           */
1710          return apply_filters( 'rest_get_max_batch_size', 25 );
1711      }
1712  
1713      /**
1714       * Serves the batch/v1 request.
1715       *
1716       * @since 5.6.0
1717       *
1718       * @param WP_REST_Request $batch_request The batch request object.
1719       * @return WP_REST_Response The generated response object.
1720       */
1721  	public function serve_batch_request_v1( WP_REST_Request $batch_request ) {
1722          $requests = array();
1723  
1724          foreach ( $batch_request['requests'] as $args ) {
1725              $parsed_url = wp_parse_url( $args['path'] );
1726  
1727              if ( false === $parsed_url ) {
1728                  $requests[] = new WP_Error( 'parse_path_failed', __( 'Could not parse the path.' ), array( 'status' => 400 ) );
1729  
1730                  continue;
1731              }
1732  
1733              $single_request = new WP_REST_Request( $args['method'] ?? 'POST', $parsed_url['path'] );
1734  
1735              if ( ! empty( $parsed_url['query'] ) ) {
1736                  $query_args = array();
1737                  wp_parse_str( $parsed_url['query'], $query_args );
1738                  $single_request->set_query_params( $query_args );
1739              }
1740  
1741              if ( ! empty( $args['body'] ) ) {
1742                  $single_request->set_body_params( $args['body'] );
1743              }
1744  
1745              if ( ! empty( $args['headers'] ) ) {
1746                  $single_request->set_headers( $args['headers'] );
1747              }
1748  
1749              $requests[] = $single_request;
1750          }
1751  
1752          $matches    = array();
1753          $validation = array();
1754          $has_error  = false;
1755  
1756          foreach ( $requests as $single_request ) {
1757              if ( is_wp_error( $single_request ) ) {
1758                  $has_error    = true;
1759                  $validation[] = $single_request;
1760                  continue;
1761              }
1762  
1763              $match     = $this->match_request_to_handler( $single_request );
1764              $matches[] = $match;
1765              $error     = null;
1766  
1767              if ( is_wp_error( $match ) ) {
1768                  $error = $match;
1769              }
1770  
1771              if ( ! $error ) {
1772                  list( $route, $handler ) = $match;
1773  
1774                  if ( isset( $handler['allow_batch'] ) ) {
1775                      $allow_batch = $handler['allow_batch'];
1776                  } else {
1777                      $route_options = $this->get_route_options( $route );
1778                      $allow_batch   = $route_options['allow_batch'] ?? false;
1779                  }
1780  
1781                  if ( ! is_array( $allow_batch ) || empty( $allow_batch['v1'] ) ) {
1782                      $error = new WP_Error(
1783                          'rest_batch_not_allowed',
1784                          __( 'The requested route does not support batch requests.' ),
1785                          array( 'status' => 400 )
1786                      );
1787                  }
1788              }
1789  
1790              if ( ! $error ) {
1791                  $check_required = $single_request->has_valid_params();
1792                  if ( is_wp_error( $check_required ) ) {
1793                      $error = $check_required;
1794                  }
1795              }
1796  
1797              if ( ! $error ) {
1798                  $check_sanitized = $single_request->sanitize_params();
1799                  if ( is_wp_error( $check_sanitized ) ) {
1800                      $error = $check_sanitized;
1801                  }
1802              }
1803  
1804              if ( $error ) {
1805                  $has_error    = true;
1806                  $validation[] = $error;
1807              } else {
1808                  $validation[] = true;
1809              }
1810          }
1811  
1812          $responses = array();
1813  
1814          if ( $has_error && 'require-all-validate' === $batch_request['validation'] ) {
1815              foreach ( $validation as $valid ) {
1816                  if ( is_wp_error( $valid ) ) {
1817                      $responses[] = $this->envelope_response( $this->error_to_response( $valid ), false )->get_data();
1818                  } else {
1819                      $responses[] = null;
1820                  }
1821              }
1822  
1823              return new WP_REST_Response(
1824                  array(
1825                      'failed'    => 'validation',
1826                      'responses' => $responses,
1827                  ),
1828                  WP_Http::MULTI_STATUS
1829              );
1830          }
1831  
1832          foreach ( $requests as $i => $single_request ) {
1833              if ( is_wp_error( $single_request ) ) {
1834                  $result      = $this->error_to_response( $single_request );
1835                  $responses[] = $this->envelope_response( $result, false )->get_data();
1836                  continue;
1837              }
1838  
1839              $clean_request = clone $single_request;
1840              $clean_request->set_url_params( array() );
1841              $clean_request->set_attributes( array() );
1842              $clean_request->set_default_params( array() );
1843  
1844              /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
1845              $result = apply_filters( 'rest_pre_dispatch', null, $this, $clean_request );
1846  
1847              if ( empty( $result ) ) {
1848                  $match = $matches[ $i ];
1849                  $error = null;
1850  
1851                  if ( is_wp_error( $validation[ $i ] ) ) {
1852                      $error = $validation[ $i ];
1853                  }
1854  
1855                  if ( is_wp_error( $match ) ) {
1856                      $result = $this->error_to_response( $match );
1857                  } else {
1858                      list( $route, $handler ) = $match;
1859  
1860                      if ( ! $error && ! is_callable( $handler['callback'] ) ) {
1861                          $error = new WP_Error(
1862                              'rest_invalid_handler',
1863                              __( 'The handler for the route is invalid' ),
1864                              array( 'status' => 500 )
1865                          );
1866                      }
1867  
1868                      $result = $this->respond_to_request( $single_request, $route, $handler, $error );
1869                  }
1870              }
1871  
1872              /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
1873              $result = apply_filters( 'rest_post_dispatch', rest_ensure_response( $result ), $this, $single_request );
1874  
1875              $responses[] = $this->envelope_response( $result, false )->get_data();
1876          }
1877  
1878          return new WP_REST_Response( array( 'responses' => $responses ), WP_Http::MULTI_STATUS );
1879      }
1880  
1881      /**
1882       * Sends an HTTP status code.
1883       *
1884       * @since 4.4.0
1885       *
1886       * @param int $code HTTP status.
1887       */
1888  	protected function set_status( $code ) {
1889          status_header( $code );
1890      }
1891  
1892      /**
1893       * Sends an HTTP header.
1894       *
1895       * @since 4.4.0
1896       *
1897       * @param string $key Header key.
1898       * @param string $value Header value.
1899       */
1900  	public function send_header( $key, $value ) {
1901          /*
1902           * Sanitize as per RFC2616 (Section 4.2):
1903           *
1904           * Any LWS that occurs between field-content MAY be replaced with a
1905           * single SP before interpreting the field value or forwarding the
1906           * message downstream.
1907           */
1908          $value = preg_replace( '/\s+/', ' ', $value );
1909          header( sprintf( '%s: %s', $key, $value ) );
1910      }
1911  
1912      /**
1913       * Sends multiple HTTP headers.
1914       *
1915       * @since 4.4.0
1916       *
1917       * @param array $headers Map of header name to header value.
1918       */
1919  	public function send_headers( $headers ) {
1920          foreach ( $headers as $key => $value ) {
1921              $this->send_header( $key, $value );
1922          }
1923      }
1924  
1925      /**
1926       * Removes an HTTP header from the current response.
1927       *
1928       * @since 4.8.0
1929       *
1930       * @param string $key Header key.
1931       */
1932  	public function remove_header( $key ) {
1933          header_remove( $key );
1934      }
1935  
1936      /**
1937       * Retrieves the raw request entity (body).
1938       *
1939       * @since 4.4.0
1940       *
1941       * @global string $HTTP_RAW_POST_DATA Raw post data.
1942       *
1943       * @return string Raw request data.
1944       */
1945  	public static function get_raw_data() {
1946          // phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
1947          global $HTTP_RAW_POST_DATA;
1948  
1949          // $HTTP_RAW_POST_DATA was deprecated in PHP 5.6 and removed in PHP 7.0.
1950          if ( ! isset( $HTTP_RAW_POST_DATA ) ) {
1951              $HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
1952          }
1953  
1954          return $HTTP_RAW_POST_DATA;
1955          // phpcs:enable
1956      }
1957  
1958      /**
1959       * Extracts headers from a PHP-style $_SERVER array.
1960       *
1961       * @since 4.4.0
1962       *
1963       * @param array $server Associative array similar to `$_SERVER`.
1964       * @return array Headers extracted from the input.
1965       */
1966  	public function get_headers( $server ) {
1967          $headers = array();
1968  
1969          // CONTENT_* headers are not prefixed with HTTP_.
1970          $additional = array(
1971              'CONTENT_LENGTH' => true,
1972              'CONTENT_MD5'    => true,
1973              'CONTENT_TYPE'   => true,
1974          );
1975  
1976          foreach ( $server as $key => $value ) {
1977              if ( str_starts_with( $key, 'HTTP_' ) ) {
1978                  $headers[ substr( $key, 5 ) ] = $value;
1979              } elseif ( 'REDIRECT_HTTP_AUTHORIZATION' === $key && empty( $server['HTTP_AUTHORIZATION'] ) ) {
1980                  /*
1981                   * In some server configurations, the authorization header is passed in this alternate location.
1982                   * Since it would not be passed in both places we do not check for both headers and resolve.
1983                   */
1984                  $headers['AUTHORIZATION'] = $value;
1985              } elseif ( isset( $additional[ $key ] ) ) {
1986                  $headers[ $key ] = $value;
1987              }
1988          }
1989  
1990          return $headers;
1991      }
1992  }


Generated : Thu Jul 16 08:20:16 2026 Cross-referenced by PHPXref