wp/wp-includes/rest-api/class-wp-rest-server.php
changeset 7 cf61fcea0001
child 9 177826044cd9
equal deleted inserted replaced
6:490d5cc509ed 7:cf61fcea0001
       
     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 class WP_REST_Server {
       
    16 
       
    17 	/**
       
    18 	 * Alias for GET transport method.
       
    19 	 *
       
    20 	 * @since 4.4.0
       
    21 	 * @var string
       
    22 	 */
       
    23 	const READABLE = 'GET';
       
    24 
       
    25 	/**
       
    26 	 * Alias for POST transport method.
       
    27 	 *
       
    28 	 * @since 4.4.0
       
    29 	 * @var string
       
    30 	 */
       
    31 	const CREATABLE = 'POST';
       
    32 
       
    33 	/**
       
    34 	 * Alias for POST, PUT, PATCH transport methods together.
       
    35 	 *
       
    36 	 * @since 4.4.0
       
    37 	 * @var string
       
    38 	 */
       
    39 	const EDITABLE = 'POST, PUT, PATCH';
       
    40 
       
    41 	/**
       
    42 	 * Alias for DELETE transport method.
       
    43 	 *
       
    44 	 * @since 4.4.0
       
    45 	 * @var string
       
    46 	 */
       
    47 	const DELETABLE = 'DELETE';
       
    48 
       
    49 	/**
       
    50 	 * Alias for GET, POST, PUT, PATCH & DELETE transport methods together.
       
    51 	 *
       
    52 	 * @since 4.4.0
       
    53 	 * @var string
       
    54 	 */
       
    55 	const ALLMETHODS = 'GET, POST, PUT, PATCH, DELETE';
       
    56 
       
    57 	/**
       
    58 	 * Namespaces registered to the server.
       
    59 	 *
       
    60 	 * @since 4.4.0
       
    61 	 * @var array
       
    62 	 */
       
    63 	protected $namespaces = array();
       
    64 
       
    65 	/**
       
    66 	 * Endpoints registered to the server.
       
    67 	 *
       
    68 	 * @since 4.4.0
       
    69 	 * @var array
       
    70 	 */
       
    71 	protected $endpoints = array();
       
    72 
       
    73 	/**
       
    74 	 * Options defined for the routes.
       
    75 	 *
       
    76 	 * @since 4.4.0
       
    77 	 * @var array
       
    78 	 */
       
    79 	protected $route_options = array();
       
    80 
       
    81 	/**
       
    82 	 * Instantiates the REST server.
       
    83 	 *
       
    84 	 * @since 4.4.0
       
    85 	 */
       
    86 	public function __construct() {
       
    87 		$this->endpoints = array(
       
    88 			// Meta endpoints.
       
    89 			'/' => array(
       
    90 				'callback' => array( $this, 'get_index' ),
       
    91 				'methods' => 'GET',
       
    92 				'args' => array(
       
    93 					'context' => array(
       
    94 						'default' => 'view',
       
    95 					),
       
    96 				),
       
    97 			),
       
    98 		);
       
    99 	}
       
   100 
       
   101 
       
   102 	/**
       
   103 	 * Checks the authentication headers if supplied.
       
   104 	 *
       
   105 	 * @since 4.4.0
       
   106 	 *
       
   107 	 * @return WP_Error|null WP_Error indicates unsuccessful login, null indicates successful
       
   108 	 *                       or no authentication provided
       
   109 	 */
       
   110 	public function check_authentication() {
       
   111 		/**
       
   112 		 * Filters REST authentication errors.
       
   113 		 *
       
   114 		 * This is used to pass a WP_Error from an authentication method back to
       
   115 		 * the API.
       
   116 		 *
       
   117 		 * Authentication methods should check first if they're being used, as
       
   118 		 * multiple authentication methods can be enabled on a site (cookies,
       
   119 		 * HTTP basic auth, OAuth). If the authentication method hooked in is
       
   120 		 * not actually being attempted, null should be returned to indicate
       
   121 		 * another authentication method should check instead. Similarly,
       
   122 		 * callbacks should ensure the value is `null` before checking for
       
   123 		 * errors.
       
   124 		 *
       
   125 		 * A WP_Error instance can be returned if an error occurs, and this should
       
   126 		 * match the format used by API methods internally (that is, the `status`
       
   127 		 * data should be used). A callback can return `true` to indicate that
       
   128 		 * the authentication method was used, and it succeeded.
       
   129 		 *
       
   130 		 * @since 4.4.0
       
   131 		 *
       
   132 		 * @param WP_Error|null|bool WP_Error if authentication error, null if authentication
       
   133 		 *                              method wasn't used, true if authentication succeeded.
       
   134 		 */
       
   135 		return apply_filters( 'rest_authentication_errors', null );
       
   136 	}
       
   137 
       
   138 	/**
       
   139 	 * Converts an error to a response object.
       
   140 	 *
       
   141 	 * This iterates over all error codes and messages to change it into a flat
       
   142 	 * array. This enables simpler client behaviour, as it is represented as a
       
   143 	 * list in JSON rather than an object/map.
       
   144 	 *
       
   145 	 * @since 4.4.0
       
   146 	 *
       
   147 	 * @param WP_Error $error WP_Error instance.
       
   148 	 * @return WP_REST_Response List of associative arrays with code and message keys.
       
   149 	 */
       
   150 	protected function error_to_response( $error ) {
       
   151 		$error_data = $error->get_error_data();
       
   152 
       
   153 		if ( is_array( $error_data ) && isset( $error_data['status'] ) ) {
       
   154 			$status = $error_data['status'];
       
   155 		} else {
       
   156 			$status = 500;
       
   157 		}
       
   158 
       
   159 		$errors = array();
       
   160 
       
   161 		foreach ( (array) $error->errors as $code => $messages ) {
       
   162 			foreach ( (array) $messages as $message ) {
       
   163 				$errors[] = array( 'code' => $code, 'message' => $message, 'data' => $error->get_error_data( $code ) );
       
   164 			}
       
   165 		}
       
   166 
       
   167 		$data = $errors[0];
       
   168 		if ( count( $errors ) > 1 ) {
       
   169 			// Remove the primary error.
       
   170 			array_shift( $errors );
       
   171 			$data['additional_errors'] = $errors;
       
   172 		}
       
   173 
       
   174 		$response = new WP_REST_Response( $data, $status );
       
   175 
       
   176 		return $response;
       
   177 	}
       
   178 
       
   179 	/**
       
   180 	 * Retrieves an appropriate error representation in JSON.
       
   181 	 *
       
   182 	 * Note: This should only be used in WP_REST_Server::serve_request(), as it
       
   183 	 * cannot handle WP_Error internally. All callbacks and other internal methods
       
   184 	 * should instead return a WP_Error with the data set to an array that includes
       
   185 	 * a 'status' key, with the value being the HTTP status to send.
       
   186 	 *
       
   187 	 * @since 4.4.0
       
   188 	 *
       
   189 	 * @param string $code    WP_Error-style code.
       
   190 	 * @param string $message Human-readable message.
       
   191 	 * @param int    $status  Optional. HTTP status code to send. Default null.
       
   192 	 * @return string JSON representation of the error
       
   193 	 */
       
   194 	protected function json_error( $code, $message, $status = null ) {
       
   195 		if ( $status ) {
       
   196 			$this->set_status( $status );
       
   197 		}
       
   198 
       
   199 		$error = compact( 'code', 'message' );
       
   200 
       
   201 		return wp_json_encode( $error );
       
   202 	}
       
   203 
       
   204 	/**
       
   205 	 * Handles serving an API request.
       
   206 	 *
       
   207 	 * Matches the current server URI to a route and runs the first matching
       
   208 	 * callback then outputs a JSON representation of the returned value.
       
   209 	 *
       
   210 	 * @since 4.4.0
       
   211 	 *
       
   212 	 * @see WP_REST_Server::dispatch()
       
   213 	 *
       
   214 	 * @param string $path Optional. The request route. If not set, `$_SERVER['PATH_INFO']` will be used.
       
   215 	 *                     Default null.
       
   216 	 * @return false|null Null if not served and a HEAD request, false otherwise.
       
   217 	 */
       
   218 	public function serve_request( $path = null ) {
       
   219 		$content_type = isset( $_GET['_jsonp'] ) ? 'application/javascript' : 'application/json';
       
   220 		$this->send_header( 'Content-Type', $content_type . '; charset=' . get_option( 'blog_charset' ) );
       
   221 		$this->send_header( 'X-Robots-Tag', 'noindex' );
       
   222 
       
   223 		$api_root = get_rest_url();
       
   224 		if ( ! empty( $api_root ) ) {
       
   225 			$this->send_header( 'Link', '<' . esc_url_raw( $api_root ) . '>; rel="https://api.w.org/"' );
       
   226 		}
       
   227 
       
   228 		/*
       
   229 		 * Mitigate possible JSONP Flash attacks.
       
   230 		 *
       
   231 		 * https://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
       
   232 		 */
       
   233 		$this->send_header( 'X-Content-Type-Options', 'nosniff' );
       
   234 		$this->send_header( 'Access-Control-Expose-Headers', 'X-WP-Total, X-WP-TotalPages' );
       
   235 		$this->send_header( 'Access-Control-Allow-Headers', 'Authorization, Content-Type' );
       
   236 
       
   237 		/**
       
   238 		 * Send nocache headers on authenticated requests.
       
   239 		 *
       
   240 		 * @since 4.4.0
       
   241 		 *
       
   242 		 * @param bool $rest_send_nocache_headers Whether to send no-cache headers.
       
   243 		 */
       
   244 		$send_no_cache_headers = apply_filters( 'rest_send_nocache_headers', is_user_logged_in() );
       
   245 		if ( $send_no_cache_headers ) {
       
   246 			foreach ( wp_get_nocache_headers() as $header => $header_value ) {
       
   247 				if ( empty( $header_value ) ) {
       
   248 					$this->remove_header( $header );
       
   249 				} else {
       
   250 					$this->send_header( $header, $header_value );
       
   251 				}
       
   252 			}
       
   253 		}
       
   254 
       
   255 		/**
       
   256 		 * Filters whether the REST API is enabled.
       
   257 		 *
       
   258 		 * @since 4.4.0
       
   259 		 * @deprecated 4.7.0 Use the rest_authentication_errors filter to restrict access to the API
       
   260 		 *
       
   261 		 * @param bool $rest_enabled Whether the REST API is enabled. Default true.
       
   262 		 */
       
   263 		apply_filters_deprecated( 'rest_enabled', array( true ), '4.7.0', 'rest_authentication_errors',
       
   264 			__( 'The REST API can no longer be completely disabled, the rest_authentication_errors filter can be used to restrict access to the API, instead.' )
       
   265 		);
       
   266 
       
   267 		/**
       
   268 		 * Filters whether jsonp is enabled.
       
   269 		 *
       
   270 		 * @since 4.4.0
       
   271 		 *
       
   272 		 * @param bool $jsonp_enabled Whether jsonp is enabled. Default true.
       
   273 		 */
       
   274 		$jsonp_enabled = apply_filters( 'rest_jsonp_enabled', true );
       
   275 
       
   276 		$jsonp_callback = null;
       
   277 
       
   278 		if ( isset( $_GET['_jsonp'] ) ) {
       
   279 			if ( ! $jsonp_enabled ) {
       
   280 				echo $this->json_error( 'rest_callback_disabled', __( 'JSONP support is disabled on this site.' ), 400 );
       
   281 				return false;
       
   282 			}
       
   283 
       
   284 			$jsonp_callback = $_GET['_jsonp'];
       
   285 			if ( ! wp_check_jsonp_callback( $jsonp_callback ) ) {
       
   286 				echo $this->json_error( 'rest_callback_invalid', __( 'Invalid JSONP callback function.' ), 400 );
       
   287 				return false;
       
   288 			}
       
   289 		}
       
   290 
       
   291 		if ( empty( $path ) ) {
       
   292 			if ( isset( $_SERVER['PATH_INFO'] ) ) {
       
   293 				$path = $_SERVER['PATH_INFO'];
       
   294 			} else {
       
   295 				$path = '/';
       
   296 			}
       
   297 		}
       
   298 
       
   299 		$request = new WP_REST_Request( $_SERVER['REQUEST_METHOD'], $path );
       
   300 
       
   301 		$request->set_query_params( wp_unslash( $_GET ) );
       
   302 		$request->set_body_params( wp_unslash( $_POST ) );
       
   303 		$request->set_file_params( $_FILES );
       
   304 		$request->set_headers( $this->get_headers( wp_unslash( $_SERVER ) ) );
       
   305 		$request->set_body( $this->get_raw_data() );
       
   306 
       
   307 		/*
       
   308 		 * HTTP method override for clients that can't use PUT/PATCH/DELETE. First, we check
       
   309 		 * $_GET['_method']. If that is not set, we check for the HTTP_X_HTTP_METHOD_OVERRIDE
       
   310 		 * header.
       
   311 		 */
       
   312 		if ( isset( $_GET['_method'] ) ) {
       
   313 			$request->set_method( $_GET['_method'] );
       
   314 		} elseif ( isset( $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] ) ) {
       
   315 			$request->set_method( $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] );
       
   316 		}
       
   317 
       
   318 		$result = $this->check_authentication();
       
   319 
       
   320 		if ( ! is_wp_error( $result ) ) {
       
   321 			$result = $this->dispatch( $request );
       
   322 		}
       
   323 
       
   324 		// Normalize to either WP_Error or WP_REST_Response...
       
   325 		$result = rest_ensure_response( $result );
       
   326 
       
   327 		// ...then convert WP_Error across.
       
   328 		if ( is_wp_error( $result ) ) {
       
   329 			$result = $this->error_to_response( $result );
       
   330 		}
       
   331 
       
   332 		/**
       
   333 		 * Filters the API response.
       
   334 		 *
       
   335 		 * Allows modification of the response before returning.
       
   336 		 *
       
   337 		 * @since 4.4.0
       
   338 		 * @since 4.5.0 Applied to embedded responses.
       
   339 		 *
       
   340 		 * @param WP_HTTP_Response $result  Result to send to the client. Usually a WP_REST_Response.
       
   341 		 * @param WP_REST_Server   $this    Server instance.
       
   342 		 * @param WP_REST_Request  $request Request used to generate the response.
       
   343 		 */
       
   344 		$result = apply_filters( 'rest_post_dispatch', rest_ensure_response( $result ), $this, $request );
       
   345 
       
   346 		// Wrap the response in an envelope if asked for.
       
   347 		if ( isset( $_GET['_envelope'] ) ) {
       
   348 			$result = $this->envelope_response( $result, isset( $_GET['_embed'] ) );
       
   349 		}
       
   350 
       
   351 		// Send extra data from response objects.
       
   352 		$headers = $result->get_headers();
       
   353 		$this->send_headers( $headers );
       
   354 
       
   355 		$code = $result->get_status();
       
   356 		$this->set_status( $code );
       
   357 
       
   358 		/**
       
   359 		 * Filters whether the request has already been served.
       
   360 		 *
       
   361 		 * Allow sending the request manually - by returning true, the API result
       
   362 		 * will not be sent to the client.
       
   363 		 *
       
   364 		 * @since 4.4.0
       
   365 		 *
       
   366 		 * @param bool             $served  Whether the request has already been served.
       
   367 		 *                                           Default false.
       
   368 		 * @param WP_HTTP_Response $result  Result to send to the client. Usually a WP_REST_Response.
       
   369 		 * @param WP_REST_Request  $request Request used to generate the response.
       
   370 		 * @param WP_REST_Server   $this    Server instance.
       
   371 		 */
       
   372 		$served = apply_filters( 'rest_pre_serve_request', false, $result, $request, $this );
       
   373 
       
   374 		if ( ! $served ) {
       
   375 			if ( 'HEAD' === $request->get_method() ) {
       
   376 				return null;
       
   377 			}
       
   378 
       
   379 			// Embed links inside the request.
       
   380 			$result = $this->response_to_data( $result, isset( $_GET['_embed'] ) );
       
   381 
       
   382 			/**
       
   383 			 * Filters the API response.
       
   384 			 *
       
   385 			 * Allows modification of the response data after inserting
       
   386 			 * embedded data (if any) and before echoing the response data.
       
   387 			 *
       
   388 			 * @since 4.8.1
       
   389 			 *
       
   390 			 * @param array            $result  Response data to send to the client.
       
   391 			 * @param WP_REST_Server   $this    Server instance.
       
   392 			 * @param WP_REST_Request  $request Request used to generate the response.
       
   393 			 */
       
   394 			$result = apply_filters( 'rest_pre_echo_response', $result, $this, $request );
       
   395 
       
   396 			$result = wp_json_encode( $result );
       
   397 
       
   398 			$json_error_message = $this->get_json_last_error();
       
   399 			if ( $json_error_message ) {
       
   400 				$json_error_obj = new WP_Error( 'rest_encode_error', $json_error_message, array( 'status' => 500 ) );
       
   401 				$result = $this->error_to_response( $json_error_obj );
       
   402 				$result = wp_json_encode( $result->data[0] );
       
   403 			}
       
   404 
       
   405 			if ( $jsonp_callback ) {
       
   406 				// Prepend '/**/' to mitigate possible JSONP Flash attacks.
       
   407 				// https://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
       
   408 				echo '/**/' . $jsonp_callback . '(' . $result . ')';
       
   409 			} else {
       
   410 				echo $result;
       
   411 			}
       
   412 		}
       
   413 		return null;
       
   414 	}
       
   415 
       
   416 	/**
       
   417 	 * Converts a response to data to send.
       
   418 	 *
       
   419 	 * @since 4.4.0
       
   420 	 *
       
   421 	 * @param WP_REST_Response $response Response object.
       
   422 	 * @param bool             $embed    Whether links should be embedded.
       
   423 	 * @return array {
       
   424 	 *     Data with sub-requests embedded.
       
   425 	 *
       
   426 	 *     @type array [$_links]    Links.
       
   427 	 *     @type array [$_embedded] Embeddeds.
       
   428 	 * }
       
   429 	 */
       
   430 	public function response_to_data( $response, $embed ) {
       
   431 		$data  = $response->get_data();
       
   432 		$links = $this->get_compact_response_links( $response );
       
   433 
       
   434 		if ( ! empty( $links ) ) {
       
   435 			// Convert links to part of the data.
       
   436 			$data['_links'] = $links;
       
   437 		}
       
   438 		if ( $embed ) {
       
   439 			// Determine if this is a numeric array.
       
   440 			if ( wp_is_numeric_array( $data ) ) {
       
   441 				$data = array_map( array( $this, 'embed_links' ), $data );
       
   442 			} else {
       
   443 				$data = $this->embed_links( $data );
       
   444 			}
       
   445 		}
       
   446 
       
   447 		return $data;
       
   448 	}
       
   449 
       
   450 	/**
       
   451 	 * Retrieves links from a response.
       
   452 	 *
       
   453 	 * Extracts the links from a response into a structured hash, suitable for
       
   454 	 * direct output.
       
   455 	 *
       
   456 	 * @since 4.4.0
       
   457 	 * @static
       
   458 	 *
       
   459 	 * @param WP_REST_Response $response Response to extract links from.
       
   460 	 * @return array Map of link relation to list of link hashes.
       
   461 	 */
       
   462 	public static function get_response_links( $response ) {
       
   463 		$links = $response->get_links();
       
   464 		if ( empty( $links ) ) {
       
   465 			return array();
       
   466 		}
       
   467 
       
   468 		// Convert links to part of the data.
       
   469 		$data = array();
       
   470 		foreach ( $links as $rel => $items ) {
       
   471 			$data[ $rel ] = array();
       
   472 
       
   473 			foreach ( $items as $item ) {
       
   474 				$attributes = $item['attributes'];
       
   475 				$attributes['href'] = $item['href'];
       
   476 				$data[ $rel ][] = $attributes;
       
   477 			}
       
   478 		}
       
   479 
       
   480 		return $data;
       
   481 	}
       
   482 
       
   483 	/**
       
   484 	 * Retrieves the CURIEs (compact URIs) used for relations.
       
   485 	 *
       
   486 	 * Extracts the links from a response into a structured hash, suitable for
       
   487 	 * direct output.
       
   488 	 *
       
   489 	 * @since 4.5.0
       
   490 	 * @static
       
   491 	 *
       
   492 	 * @param WP_REST_Response $response Response to extract links from.
       
   493 	 * @return array Map of link relation to list of link hashes.
       
   494 	 */
       
   495 	public static function get_compact_response_links( $response ) {
       
   496 		$links = self::get_response_links( $response );
       
   497 
       
   498 		if ( empty( $links ) ) {
       
   499 			return array();
       
   500 		}
       
   501 
       
   502 		$curies = $response->get_curies();
       
   503 		$used_curies = array();
       
   504 
       
   505 		foreach ( $links as $rel => $items ) {
       
   506 
       
   507 			// Convert $rel URIs to their compact versions if they exist.
       
   508 			foreach ( $curies as $curie ) {
       
   509 				$href_prefix = substr( $curie['href'], 0, strpos( $curie['href'], '{rel}' ) );
       
   510 				if ( strpos( $rel, $href_prefix ) !== 0 ) {
       
   511 					continue;
       
   512 				}
       
   513 
       
   514 				// Relation now changes from '$uri' to '$curie:$relation'.
       
   515 				$rel_regex = str_replace( '\{rel\}', '(.+)', preg_quote( $curie['href'], '!' ) );
       
   516 				preg_match( '!' . $rel_regex . '!', $rel, $matches );
       
   517 				if ( $matches ) {
       
   518 					$new_rel = $curie['name'] . ':' . $matches[1];
       
   519 					$used_curies[ $curie['name'] ] = $curie;
       
   520 					$links[ $new_rel ] = $items;
       
   521 					unset( $links[ $rel ] );
       
   522 					break;
       
   523 				}
       
   524 			}
       
   525 		}
       
   526 
       
   527 		// Push the curies onto the start of the links array.
       
   528 		if ( $used_curies ) {
       
   529 			$links['curies'] = array_values( $used_curies );
       
   530 		}
       
   531 
       
   532 		return $links;
       
   533 	}
       
   534 
       
   535 	/**
       
   536 	 * Embeds the links from the data into the request.
       
   537 	 *
       
   538 	 * @since 4.4.0
       
   539 	 *
       
   540 	 * @param array $data Data from the request.
       
   541 	 * @return array {
       
   542 	 *     Data with sub-requests embedded.
       
   543 	 *
       
   544 	 *     @type array [$_links]    Links.
       
   545 	 *     @type array [$_embedded] Embeddeds.
       
   546 	 * }
       
   547 	 */
       
   548 	protected function embed_links( $data ) {
       
   549 		if ( empty( $data['_links'] ) ) {
       
   550 			return $data;
       
   551 		}
       
   552 
       
   553 		$embedded = array();
       
   554 
       
   555 		foreach ( $data['_links'] as $rel => $links ) {
       
   556 			// Ignore links to self, for obvious reasons.
       
   557 			if ( 'self' === $rel ) {
       
   558 				continue;
       
   559 			}
       
   560 
       
   561 			$embeds = array();
       
   562 
       
   563 			foreach ( $links as $item ) {
       
   564 				// Determine if the link is embeddable.
       
   565 				if ( empty( $item['embeddable'] ) ) {
       
   566 					// Ensure we keep the same order.
       
   567 					$embeds[] = array();
       
   568 					continue;
       
   569 				}
       
   570 
       
   571 				// Run through our internal routing and serve.
       
   572 				$request = WP_REST_Request::from_url( $item['href'] );
       
   573 				if ( ! $request ) {
       
   574 					$embeds[] = array();
       
   575 					continue;
       
   576 				}
       
   577 
       
   578 				// Embedded resources get passed context=embed.
       
   579 				if ( empty( $request['context'] ) ) {
       
   580 					$request['context'] = 'embed';
       
   581 				}
       
   582 
       
   583 				$response = $this->dispatch( $request );
       
   584 
       
   585 				/** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
       
   586 				$response = apply_filters( 'rest_post_dispatch', rest_ensure_response( $response ), $this, $request );
       
   587 
       
   588 				$embeds[] = $this->response_to_data( $response, false );
       
   589 			}
       
   590 
       
   591 			// Determine if any real links were found.
       
   592 			$has_links = count( array_filter( $embeds ) );
       
   593 
       
   594 			if ( $has_links ) {
       
   595 				$embedded[ $rel ] = $embeds;
       
   596 			}
       
   597 		}
       
   598 
       
   599 		if ( ! empty( $embedded ) ) {
       
   600 			$data['_embedded'] = $embedded;
       
   601 		}
       
   602 
       
   603 		return $data;
       
   604 	}
       
   605 
       
   606 	/**
       
   607 	 * Wraps the response in an envelope.
       
   608 	 *
       
   609 	 * The enveloping technique is used to work around browser/client
       
   610 	 * compatibility issues. Essentially, it converts the full HTTP response to
       
   611 	 * data instead.
       
   612 	 *
       
   613 	 * @since 4.4.0
       
   614 	 *
       
   615 	 * @param WP_REST_Response $response Response object.
       
   616 	 * @param bool             $embed    Whether links should be embedded.
       
   617 	 * @return WP_REST_Response New response with wrapped data
       
   618 	 */
       
   619 	public function envelope_response( $response, $embed ) {
       
   620 		$envelope = array(
       
   621 			'body'    => $this->response_to_data( $response, $embed ),
       
   622 			'status'  => $response->get_status(),
       
   623 			'headers' => $response->get_headers(),
       
   624 		);
       
   625 
       
   626 		/**
       
   627 		 * Filters the enveloped form of a response.
       
   628 		 *
       
   629 		 * @since 4.4.0
       
   630 		 *
       
   631 		 * @param array            $envelope Envelope data.
       
   632 		 * @param WP_REST_Response $response Original response data.
       
   633 		 */
       
   634 		$envelope = apply_filters( 'rest_envelope_response', $envelope, $response );
       
   635 
       
   636 		// Ensure it's still a response and return.
       
   637 		return rest_ensure_response( $envelope );
       
   638 	}
       
   639 
       
   640 	/**
       
   641 	 * Registers a route to the server.
       
   642 	 *
       
   643 	 * @since 4.4.0
       
   644 	 *
       
   645 	 * @param string $namespace  Namespace.
       
   646 	 * @param string $route      The REST route.
       
   647 	 * @param array  $route_args Route arguments.
       
   648 	 * @param bool   $override   Optional. Whether the route should be overridden if it already exists.
       
   649 	 *                           Default false.
       
   650 	 */
       
   651 	public function register_route( $namespace, $route, $route_args, $override = false ) {
       
   652 		if ( ! isset( $this->namespaces[ $namespace ] ) ) {
       
   653 			$this->namespaces[ $namespace ] = array();
       
   654 
       
   655 			$this->register_route( $namespace, '/' . $namespace, array(
       
   656 				array(
       
   657 					'methods' => self::READABLE,
       
   658 					'callback' => array( $this, 'get_namespace_index' ),
       
   659 					'args' => array(
       
   660 						'namespace' => array(
       
   661 							'default' => $namespace,
       
   662 						),
       
   663 						'context' => array(
       
   664 							'default' => 'view',
       
   665 						),
       
   666 					),
       
   667 				),
       
   668 			) );
       
   669 		}
       
   670 
       
   671 		// Associative to avoid double-registration.
       
   672 		$this->namespaces[ $namespace ][ $route ] = true;
       
   673 		$route_args['namespace'] = $namespace;
       
   674 
       
   675 		if ( $override || empty( $this->endpoints[ $route ] ) ) {
       
   676 			$this->endpoints[ $route ] = $route_args;
       
   677 		} else {
       
   678 			$this->endpoints[ $route ] = array_merge( $this->endpoints[ $route ], $route_args );
       
   679 		}
       
   680 	}
       
   681 
       
   682 	/**
       
   683 	 * Retrieves the route map.
       
   684 	 *
       
   685 	 * The route map is an associative array with path regexes as the keys. The
       
   686 	 * value is an indexed array with the callback function/method as the first
       
   687 	 * item, and a bitmask of HTTP methods as the second item (see the class
       
   688 	 * constants).
       
   689 	 *
       
   690 	 * Each route can be mapped to more than one callback by using an array of
       
   691 	 * the indexed arrays. This allows mapping e.g. GET requests to one callback
       
   692 	 * and POST requests to another.
       
   693 	 *
       
   694 	 * Note that the path regexes (array keys) must have @ escaped, as this is
       
   695 	 * used as the delimiter with preg_match()
       
   696 	 *
       
   697 	 * @since 4.4.0
       
   698 	 *
       
   699 	 * @return array `'/path/regex' => array( $callback, $bitmask )` or
       
   700 	 *               `'/path/regex' => array( array( $callback, $bitmask ), ...)`.
       
   701 	 */
       
   702 	public function get_routes() {
       
   703 
       
   704 		/**
       
   705 		 * Filters the array of available endpoints.
       
   706 		 *
       
   707 		 * @since 4.4.0
       
   708 		 *
       
   709 		 * @param array $endpoints The available endpoints. An array of matching regex patterns, each mapped
       
   710 		 *                         to an array of callbacks for the endpoint. These take the format
       
   711 		 *                         `'/path/regex' => array( $callback, $bitmask )` or
       
   712 		 *                         `'/path/regex' => array( array( $callback, $bitmask ).
       
   713 		 */
       
   714 		$endpoints = apply_filters( 'rest_endpoints', $this->endpoints );
       
   715 
       
   716 		// Normalise the endpoints.
       
   717 		$defaults = array(
       
   718 			'methods'       => '',
       
   719 			'accept_json'   => false,
       
   720 			'accept_raw'    => false,
       
   721 			'show_in_index' => true,
       
   722 			'args'          => array(),
       
   723 		);
       
   724 
       
   725 		foreach ( $endpoints as $route => &$handlers ) {
       
   726 
       
   727 			if ( isset( $handlers['callback'] ) ) {
       
   728 				// Single endpoint, add one deeper.
       
   729 				$handlers = array( $handlers );
       
   730 			}
       
   731 
       
   732 			if ( ! isset( $this->route_options[ $route ] ) ) {
       
   733 				$this->route_options[ $route ] = array();
       
   734 			}
       
   735 
       
   736 			foreach ( $handlers as $key => &$handler ) {
       
   737 
       
   738 				if ( ! is_numeric( $key ) ) {
       
   739 					// Route option, move it to the options.
       
   740 					$this->route_options[ $route ][ $key ] = $handler;
       
   741 					unset( $handlers[ $key ] );
       
   742 					continue;
       
   743 				}
       
   744 
       
   745 				$handler = wp_parse_args( $handler, $defaults );
       
   746 
       
   747 				// Allow comma-separated HTTP methods.
       
   748 				if ( is_string( $handler['methods'] ) ) {
       
   749 					$methods = explode( ',', $handler['methods'] );
       
   750 				} elseif ( is_array( $handler['methods'] ) ) {
       
   751 					$methods = $handler['methods'];
       
   752 				} else {
       
   753 					$methods = array();
       
   754 				}
       
   755 
       
   756 				$handler['methods'] = array();
       
   757 
       
   758 				foreach ( $methods as $method ) {
       
   759 					$method = strtoupper( trim( $method ) );
       
   760 					$handler['methods'][ $method ] = true;
       
   761 				}
       
   762 			}
       
   763 		}
       
   764 
       
   765 		return $endpoints;
       
   766 	}
       
   767 
       
   768 	/**
       
   769 	 * Retrieves namespaces registered on the server.
       
   770 	 *
       
   771 	 * @since 4.4.0
       
   772 	 *
       
   773 	 * @return array List of registered namespaces.
       
   774 	 */
       
   775 	public function get_namespaces() {
       
   776 		return array_keys( $this->namespaces );
       
   777 	}
       
   778 
       
   779 	/**
       
   780 	 * Retrieves specified options for a route.
       
   781 	 *
       
   782 	 * @since 4.4.0
       
   783 	 *
       
   784 	 * @param string $route Route pattern to fetch options for.
       
   785 	 * @return array|null Data as an associative array if found, or null if not found.
       
   786 	 */
       
   787 	public function get_route_options( $route ) {
       
   788 		if ( ! isset( $this->route_options[ $route ] ) ) {
       
   789 			return null;
       
   790 		}
       
   791 
       
   792 		return $this->route_options[ $route ];
       
   793 	}
       
   794 
       
   795 	/**
       
   796 	 * Matches the request to a callback and call it.
       
   797 	 *
       
   798 	 * @since 4.4.0
       
   799 	 *
       
   800 	 * @param WP_REST_Request $request Request to attempt dispatching.
       
   801 	 * @return WP_REST_Response Response returned by the callback.
       
   802 	 */
       
   803 	public function dispatch( $request ) {
       
   804 		/**
       
   805 		 * Filters the pre-calculated result of a REST dispatch request.
       
   806 		 *
       
   807 		 * Allow hijacking the request before dispatching by returning a non-empty. The returned value
       
   808 		 * will be used to serve the request instead.
       
   809 		 *
       
   810 		 * @since 4.4.0
       
   811 		 *
       
   812 		 * @param mixed           $result  Response to replace the requested version with. Can be anything
       
   813 		 *                                 a normal endpoint can return, or null to not hijack the request.
       
   814 		 * @param WP_REST_Server  $this    Server instance.
       
   815 		 * @param WP_REST_Request $request Request used to generate the response.
       
   816 		 */
       
   817 		$result = apply_filters( 'rest_pre_dispatch', null, $this, $request );
       
   818 
       
   819 		if ( ! empty( $result ) ) {
       
   820 			return $result;
       
   821 		}
       
   822 
       
   823 		$method = $request->get_method();
       
   824 		$path   = $request->get_route();
       
   825 
       
   826 		foreach ( $this->get_routes() as $route => $handlers ) {
       
   827 			$match = preg_match( '@^' . $route . '$@i', $path, $matches );
       
   828 
       
   829 			if ( ! $match ) {
       
   830 				continue;
       
   831 			}
       
   832 
       
   833 			$args = array();
       
   834 			foreach ( $matches as $param => $value ) {
       
   835 				if ( ! is_int( $param ) ) {
       
   836 					$args[ $param ] = $value;
       
   837 				}
       
   838 			}
       
   839 
       
   840 			foreach ( $handlers as $handler ) {
       
   841 				$callback  = $handler['callback'];
       
   842 				$response = null;
       
   843 
       
   844 				// Fallback to GET method if no HEAD method is registered.
       
   845 				$checked_method = $method;
       
   846 				if ( 'HEAD' === $method && empty( $handler['methods']['HEAD'] ) ) {
       
   847 					$checked_method = 'GET';
       
   848 				}
       
   849 				if ( empty( $handler['methods'][ $checked_method ] ) ) {
       
   850 					continue;
       
   851 				}
       
   852 
       
   853 				if ( ! is_callable( $callback ) ) {
       
   854 					$response = new WP_Error( 'rest_invalid_handler', __( 'The handler for the route is invalid' ), array( 'status' => 500 ) );
       
   855 				}
       
   856 
       
   857 				if ( ! is_wp_error( $response ) ) {
       
   858 					// Remove the redundant preg_match argument.
       
   859 					unset( $args[0] );
       
   860 
       
   861 					$request->set_url_params( $args );
       
   862 					$request->set_attributes( $handler );
       
   863 
       
   864 					$defaults = array();
       
   865 
       
   866 					foreach ( $handler['args'] as $arg => $options ) {
       
   867 						if ( isset( $options['default'] ) ) {
       
   868 							$defaults[ $arg ] = $options['default'];
       
   869 						}
       
   870 					}
       
   871 
       
   872 					$request->set_default_params( $defaults );
       
   873 
       
   874 					$check_required = $request->has_valid_params();
       
   875 					if ( is_wp_error( $check_required ) ) {
       
   876 						$response = $check_required;
       
   877 					} else {
       
   878 						$check_sanitized = $request->sanitize_params();
       
   879 						if ( is_wp_error( $check_sanitized ) ) {
       
   880 							$response = $check_sanitized;
       
   881 						}
       
   882 					}
       
   883 				}
       
   884 
       
   885 				/**
       
   886 				 * Filters the response before executing any REST API callbacks.
       
   887 				 *
       
   888 				 * Allows plugins to perform additional validation after a
       
   889 				 * request is initialized and matched to a registered route,
       
   890 				 * but before it is executed.
       
   891 				 *
       
   892 				 * Note that this filter will not be called for requests that
       
   893 				 * fail to authenticate or match to a registered route.
       
   894 				 *
       
   895 				 * @since 4.7.0
       
   896 				 *
       
   897 				 * @param WP_HTTP_Response $response Result to send to the client. Usually a WP_REST_Response.
       
   898 				 * @param WP_REST_Server   $handler  ResponseHandler instance (usually WP_REST_Server).
       
   899 				 * @param WP_REST_Request  $request  Request used to generate the response.
       
   900 				 */
       
   901 				$response = apply_filters( 'rest_request_before_callbacks', $response, $handler, $request );
       
   902 
       
   903 				if ( ! is_wp_error( $response ) ) {
       
   904 					// Check permission specified on the route.
       
   905 					if ( ! empty( $handler['permission_callback'] ) ) {
       
   906 						$permission = call_user_func( $handler['permission_callback'], $request );
       
   907 
       
   908 						if ( is_wp_error( $permission ) ) {
       
   909 							$response = $permission;
       
   910 						} elseif ( false === $permission || null === $permission ) {
       
   911 							$response = new WP_Error( 'rest_forbidden', __( 'Sorry, you are not allowed to do that.' ), array( 'status' => rest_authorization_required_code() ) );
       
   912 						}
       
   913 					}
       
   914 				}
       
   915 
       
   916 				if ( ! is_wp_error( $response ) ) {
       
   917 					/**
       
   918 					 * Filters the REST dispatch request result.
       
   919 					 *
       
   920 					 * Allow plugins to override dispatching the request.
       
   921 					 *
       
   922 					 * @since 4.4.0
       
   923 					 * @since 4.5.0 Added `$route` and `$handler` parameters.
       
   924 					 *
       
   925 					 * @param bool            $dispatch_result Dispatch result, will be used if not empty.
       
   926 					 * @param WP_REST_Request $request         Request used to generate the response.
       
   927 					 * @param string          $route           Route matched for the request.
       
   928 					 * @param array           $handler         Route handler used for the request.
       
   929 					 */
       
   930 					$dispatch_result = apply_filters( 'rest_dispatch_request', null, $request, $route, $handler );
       
   931 
       
   932 					// Allow plugins to halt the request via this filter.
       
   933 					if ( null !== $dispatch_result ) {
       
   934 						$response = $dispatch_result;
       
   935 					} else {
       
   936 						$response = call_user_func( $callback, $request );
       
   937 					}
       
   938 				}
       
   939 
       
   940 				/**
       
   941 				 * Filters the response immediately after executing any REST API
       
   942 				 * callbacks.
       
   943 				 *
       
   944 				 * Allows plugins to perform any needed cleanup, for example,
       
   945 				 * to undo changes made during the {@see 'rest_request_before_callbacks'}
       
   946 				 * filter.
       
   947 				 *
       
   948 				 * Note that this filter will not be called for requests that
       
   949 				 * fail to authenticate or match to a registered route.
       
   950 				 *
       
   951 				 * Note that an endpoint's `permission_callback` can still be
       
   952 				 * called after this filter - see `rest_send_allow_header()`.
       
   953 				 *
       
   954 				 * @since 4.7.0
       
   955 				 *
       
   956 				 * @param WP_HTTP_Response $response Result to send to the client. Usually a WP_REST_Response.
       
   957 				 * @param WP_REST_Server   $handler  ResponseHandler instance (usually WP_REST_Server).
       
   958 				 * @param WP_REST_Request  $request  Request used to generate the response.
       
   959 				 */
       
   960 				$response = apply_filters( 'rest_request_after_callbacks', $response, $handler, $request );
       
   961 
       
   962 				if ( is_wp_error( $response ) ) {
       
   963 					$response = $this->error_to_response( $response );
       
   964 				} else {
       
   965 					$response = rest_ensure_response( $response );
       
   966 				}
       
   967 
       
   968 				$response->set_matched_route( $route );
       
   969 				$response->set_matched_handler( $handler );
       
   970 
       
   971 				return $response;
       
   972 			}
       
   973 		}
       
   974 
       
   975 		return $this->error_to_response( new WP_Error( 'rest_no_route', __( 'No route was found matching the URL and request method' ), array( 'status' => 404 ) ) );
       
   976 	}
       
   977 
       
   978 	/**
       
   979 	 * Returns if an error occurred during most recent JSON encode/decode.
       
   980 	 *
       
   981 	 * Strings to be translated will be in format like
       
   982 	 * "Encoding error: Maximum stack depth exceeded".
       
   983 	 *
       
   984 	 * @since 4.4.0
       
   985 	 *
       
   986 	 * @return bool|string Boolean false or string error message.
       
   987 	 */
       
   988 	protected function get_json_last_error() {
       
   989 		// See https://core.trac.wordpress.org/ticket/27799.
       
   990 		if ( ! function_exists( 'json_last_error' ) ) {
       
   991 			return false;
       
   992 		}
       
   993 
       
   994 		$last_error_code = json_last_error();
       
   995 
       
   996 		if ( ( defined( 'JSON_ERROR_NONE' ) && JSON_ERROR_NONE === $last_error_code ) || empty( $last_error_code ) ) {
       
   997 			return false;
       
   998 		}
       
   999 
       
  1000 		return json_last_error_msg();
       
  1001 	}
       
  1002 
       
  1003 	/**
       
  1004 	 * Retrieves the site index.
       
  1005 	 *
       
  1006 	 * This endpoint describes the capabilities of the site.
       
  1007 	 *
       
  1008 	 * @since 4.4.0
       
  1009 	 *
       
  1010 	 * @param array $request {
       
  1011 	 *     Request.
       
  1012 	 *
       
  1013 	 *     @type string $context Context.
       
  1014 	 * }
       
  1015 	 * @return array Index entity
       
  1016 	 */
       
  1017 	public function get_index( $request ) {
       
  1018 		// General site data.
       
  1019 		$available = array(
       
  1020 			'name'            => get_option( 'blogname' ),
       
  1021 			'description'     => get_option( 'blogdescription' ),
       
  1022 			'url'             => get_option( 'siteurl' ),
       
  1023 			'home'            => home_url(),
       
  1024 			'gmt_offset'      => get_option( 'gmt_offset' ),
       
  1025 			'timezone_string' => get_option( 'timezone_string' ),
       
  1026 			'namespaces'      => array_keys( $this->namespaces ),
       
  1027 			'authentication'  => array(),
       
  1028 			'routes'          => $this->get_data_for_routes( $this->get_routes(), $request['context'] ),
       
  1029 		);
       
  1030 
       
  1031 		$response = new WP_REST_Response( $available );
       
  1032 
       
  1033 		$response->add_link( 'help', 'http://v2.wp-api.org/' );
       
  1034 
       
  1035 		/**
       
  1036 		 * Filters the API root index data.
       
  1037 		 *
       
  1038 		 * This contains the data describing the API. This includes information
       
  1039 		 * about supported authentication schemes, supported namespaces, routes
       
  1040 		 * available on the API, and a small amount of data about the site.
       
  1041 		 *
       
  1042 		 * @since 4.4.0
       
  1043 		 *
       
  1044 		 * @param WP_REST_Response $response Response data.
       
  1045 		 */
       
  1046 		return apply_filters( 'rest_index', $response );
       
  1047 	}
       
  1048 
       
  1049 	/**
       
  1050 	 * Retrieves the index for a namespace.
       
  1051 	 *
       
  1052 	 * @since 4.4.0
       
  1053 	 *
       
  1054 	 * @param WP_REST_Request $request REST request instance.
       
  1055 	 * @return WP_REST_Response|WP_Error WP_REST_Response instance if the index was found,
       
  1056 	 *                                   WP_Error if the namespace isn't set.
       
  1057 	 */
       
  1058 	public function get_namespace_index( $request ) {
       
  1059 		$namespace = $request['namespace'];
       
  1060 
       
  1061 		if ( ! isset( $this->namespaces[ $namespace ] ) ) {
       
  1062 			return new WP_Error( 'rest_invalid_namespace', __( 'The specified namespace could not be found.' ), array( 'status' => 404 ) );
       
  1063 		}
       
  1064 
       
  1065 		$routes = $this->namespaces[ $namespace ];
       
  1066 		$endpoints = array_intersect_key( $this->get_routes(), $routes );
       
  1067 
       
  1068 		$data = array(
       
  1069 			'namespace' => $namespace,
       
  1070 			'routes' => $this->get_data_for_routes( $endpoints, $request['context'] ),
       
  1071 		);
       
  1072 		$response = rest_ensure_response( $data );
       
  1073 
       
  1074 		// Link to the root index.
       
  1075 		$response->add_link( 'up', rest_url( '/' ) );
       
  1076 
       
  1077 		/**
       
  1078 		 * Filters the namespace index data.
       
  1079 		 *
       
  1080 		 * This typically is just the route data for the namespace, but you can
       
  1081 		 * add any data you'd like here.
       
  1082 		 *
       
  1083 		 * @since 4.4.0
       
  1084 		 *
       
  1085 		 * @param WP_REST_Response $response Response data.
       
  1086 		 * @param WP_REST_Request  $request  Request data. The namespace is passed as the 'namespace' parameter.
       
  1087 		 */
       
  1088 		return apply_filters( 'rest_namespace_index', $response, $request );
       
  1089 	}
       
  1090 
       
  1091 	/**
       
  1092 	 * Retrieves the publicly-visible data for routes.
       
  1093 	 *
       
  1094 	 * @since 4.4.0
       
  1095 	 *
       
  1096 	 * @param array  $routes  Routes to get data for.
       
  1097 	 * @param string $context Optional. Context for data. Accepts 'view' or 'help'. Default 'view'.
       
  1098 	 * @return array Route data to expose in indexes.
       
  1099 	 */
       
  1100 	public function get_data_for_routes( $routes, $context = 'view' ) {
       
  1101 		$available = array();
       
  1102 
       
  1103 		// Find the available routes.
       
  1104 		foreach ( $routes as $route => $callbacks ) {
       
  1105 			$data = $this->get_data_for_route( $route, $callbacks, $context );
       
  1106 			if ( empty( $data ) ) {
       
  1107 				continue;
       
  1108 			}
       
  1109 
       
  1110 			/**
       
  1111 			 * Filters the REST endpoint data.
       
  1112 			 *
       
  1113 			 * @since 4.4.0
       
  1114 			 *
       
  1115 			 * @param WP_REST_Request $request Request data. The namespace is passed as the 'namespace' parameter.
       
  1116 			 */
       
  1117 			$available[ $route ] = apply_filters( 'rest_endpoints_description', $data );
       
  1118 		}
       
  1119 
       
  1120 		/**
       
  1121 		 * Filters the publicly-visible data for routes.
       
  1122 		 *
       
  1123 		 * This data is exposed on indexes and can be used by clients or
       
  1124 		 * developers to investigate the site and find out how to use it. It
       
  1125 		 * acts as a form of self-documentation.
       
  1126 		 *
       
  1127 		 * @since 4.4.0
       
  1128 		 *
       
  1129 		 * @param array $available Map of route to route data.
       
  1130 		 * @param array $routes    Internal route data as an associative array.
       
  1131 		 */
       
  1132 		return apply_filters( 'rest_route_data', $available, $routes );
       
  1133 	}
       
  1134 
       
  1135 	/**
       
  1136 	 * Retrieves publicly-visible data for the route.
       
  1137 	 *
       
  1138 	 * @since 4.4.0
       
  1139 	 *
       
  1140 	 * @param string $route     Route to get data for.
       
  1141 	 * @param array  $callbacks Callbacks to convert to data.
       
  1142 	 * @param string $context   Optional. Context for the data. Accepts 'view' or 'help'. Default 'view'.
       
  1143 	 * @return array|null Data for the route, or null if no publicly-visible data.
       
  1144 	 */
       
  1145 	public function get_data_for_route( $route, $callbacks, $context = 'view' ) {
       
  1146 		$data = array(
       
  1147 			'namespace' => '',
       
  1148 			'methods' => array(),
       
  1149 			'endpoints' => array(),
       
  1150 		);
       
  1151 
       
  1152 		if ( isset( $this->route_options[ $route ] ) ) {
       
  1153 			$options = $this->route_options[ $route ];
       
  1154 
       
  1155 			if ( isset( $options['namespace'] ) ) {
       
  1156 				$data['namespace'] = $options['namespace'];
       
  1157 			}
       
  1158 
       
  1159 			if ( isset( $options['schema'] ) && 'help' === $context ) {
       
  1160 				$data['schema'] = call_user_func( $options['schema'] );
       
  1161 			}
       
  1162 		}
       
  1163 
       
  1164 		$route = preg_replace( '#\(\?P<(\w+?)>.*?\)#', '{$1}', $route );
       
  1165 
       
  1166 		foreach ( $callbacks as $callback ) {
       
  1167 			// Skip to the next route if any callback is hidden.
       
  1168 			if ( empty( $callback['show_in_index'] ) ) {
       
  1169 				continue;
       
  1170 			}
       
  1171 
       
  1172 			$data['methods'] = array_merge( $data['methods'], array_keys( $callback['methods'] ) );
       
  1173 			$endpoint_data = array(
       
  1174 				'methods' => array_keys( $callback['methods'] ),
       
  1175 			);
       
  1176 
       
  1177 			if ( isset( $callback['args'] ) ) {
       
  1178 				$endpoint_data['args'] = array();
       
  1179 				foreach ( $callback['args'] as $key => $opts ) {
       
  1180 					$arg_data = array(
       
  1181 						'required' => ! empty( $opts['required'] ),
       
  1182 					);
       
  1183 					if ( isset( $opts['default'] ) ) {
       
  1184 						$arg_data['default'] = $opts['default'];
       
  1185 					}
       
  1186 					if ( isset( $opts['enum'] ) ) {
       
  1187 						$arg_data['enum'] = $opts['enum'];
       
  1188 					}
       
  1189 					if ( isset( $opts['description'] ) ) {
       
  1190 						$arg_data['description'] = $opts['description'];
       
  1191 					}
       
  1192 					if ( isset( $opts['type'] ) ) {
       
  1193 						$arg_data['type'] = $opts['type'];
       
  1194 					}
       
  1195 					if ( isset( $opts['items'] ) ) {
       
  1196 						$arg_data['items'] = $opts['items'];
       
  1197 					}
       
  1198 					$endpoint_data['args'][ $key ] = $arg_data;
       
  1199 				}
       
  1200 			}
       
  1201 
       
  1202 			$data['endpoints'][] = $endpoint_data;
       
  1203 
       
  1204 			// For non-variable routes, generate links.
       
  1205 			if ( strpos( $route, '{' ) === false ) {
       
  1206 				$data['_links'] = array(
       
  1207 					'self' => rest_url( $route ),
       
  1208 				);
       
  1209 			}
       
  1210 		}
       
  1211 
       
  1212 		if ( empty( $data['methods'] ) ) {
       
  1213 			// No methods supported, hide the route.
       
  1214 			return null;
       
  1215 		}
       
  1216 
       
  1217 		return $data;
       
  1218 	}
       
  1219 
       
  1220 	/**
       
  1221 	 * Sends an HTTP status code.
       
  1222 	 *
       
  1223 	 * @since 4.4.0
       
  1224 	 *
       
  1225 	 * @param int $code HTTP status.
       
  1226 	 */
       
  1227 	protected function set_status( $code ) {
       
  1228 		status_header( $code );
       
  1229 	}
       
  1230 
       
  1231 	/**
       
  1232 	 * Sends an HTTP header.
       
  1233 	 *
       
  1234 	 * @since 4.4.0
       
  1235 	 *
       
  1236 	 * @param string $key Header key.
       
  1237 	 * @param string $value Header value.
       
  1238 	 */
       
  1239 	public function send_header( $key, $value ) {
       
  1240 		/*
       
  1241 		 * Sanitize as per RFC2616 (Section 4.2):
       
  1242 		 *
       
  1243 		 * Any LWS that occurs between field-content MAY be replaced with a
       
  1244 		 * single SP before interpreting the field value or forwarding the
       
  1245 		 * message downstream.
       
  1246 		 */
       
  1247 		$value = preg_replace( '/\s+/', ' ', $value );
       
  1248 		header( sprintf( '%s: %s', $key, $value ) );
       
  1249 	}
       
  1250 
       
  1251 	/**
       
  1252 	 * Sends multiple HTTP headers.
       
  1253 	 *
       
  1254 	 * @since 4.4.0
       
  1255 	 *
       
  1256 	 * @param array $headers Map of header name to header value.
       
  1257 	 */
       
  1258 	public function send_headers( $headers ) {
       
  1259 		foreach ( $headers as $key => $value ) {
       
  1260 			$this->send_header( $key, $value );
       
  1261 		}
       
  1262 	}
       
  1263 
       
  1264 	/**
       
  1265 	 * Removes an HTTP header from the current response.
       
  1266 	 *
       
  1267 	 * @since 4.8.0
       
  1268 	 *
       
  1269 	 * @param string $key Header key.
       
  1270 	 */
       
  1271 	public function remove_header( $key ) {
       
  1272 		if ( function_exists( 'header_remove' ) ) {
       
  1273 			// In PHP 5.3+ there is a way to remove an already set header.
       
  1274 			header_remove( $key );
       
  1275 		} else {
       
  1276 			// In PHP 5.2, send an empty header, but only as a last resort to
       
  1277 			// override a header already sent.
       
  1278 			foreach ( headers_list() as $header ) {
       
  1279 				if ( 0 === stripos( $header, "$key:" ) ) {
       
  1280 					$this->send_header( $key, '' );
       
  1281 					break;
       
  1282 				}
       
  1283 			}
       
  1284 		}
       
  1285 	}
       
  1286 
       
  1287 	/**
       
  1288 	 * Retrieves the raw request entity (body).
       
  1289 	 *
       
  1290 	 * @since 4.4.0
       
  1291 	 *
       
  1292 	 * @global string $HTTP_RAW_POST_DATA Raw post data.
       
  1293 	 *
       
  1294 	 * @return string Raw request data.
       
  1295 	 */
       
  1296 	public static function get_raw_data() {
       
  1297 		global $HTTP_RAW_POST_DATA;
       
  1298 
       
  1299 		/*
       
  1300 		 * A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default,
       
  1301 		 * but we can do it ourself.
       
  1302 		 */
       
  1303 		if ( ! isset( $HTTP_RAW_POST_DATA ) ) {
       
  1304 			$HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
       
  1305 		}
       
  1306 
       
  1307 		return $HTTP_RAW_POST_DATA;
       
  1308 	}
       
  1309 
       
  1310 	/**
       
  1311 	 * Extracts headers from a PHP-style $_SERVER array.
       
  1312 	 *
       
  1313 	 * @since 4.4.0
       
  1314 	 *
       
  1315 	 * @param array $server Associative array similar to `$_SERVER`.
       
  1316 	 * @return array Headers extracted from the input.
       
  1317 	 */
       
  1318 	public function get_headers( $server ) {
       
  1319 		$headers = array();
       
  1320 
       
  1321 		// CONTENT_* headers are not prefixed with HTTP_.
       
  1322 		$additional = array( 'CONTENT_LENGTH' => true, 'CONTENT_MD5' => true, 'CONTENT_TYPE' => true );
       
  1323 
       
  1324 		foreach ( $server as $key => $value ) {
       
  1325 			if ( strpos( $key, 'HTTP_' ) === 0 ) {
       
  1326 				$headers[ substr( $key, 5 ) ] = $value;
       
  1327 			} elseif ( isset( $additional[ $key ] ) ) {
       
  1328 				$headers[ $key ] = $value;
       
  1329 			}
       
  1330 		}
       
  1331 
       
  1332 		return $headers;
       
  1333 	}
       
  1334 }