PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 12.3.2
Jetpack – WP Security, Backup, Speed, & Growth v12.3.2
12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 13.7.2 13.8.3 13.9.2 14.0.1 14.1.1 14.2.2 14.3.1 14.4.2 All 500 releases
jetpack / _inc / lib / core-api / wpcom-endpoints / trait-wpcom-rest-api-proxy-request-trait.php
trait-wpcom-rest-api-proxy-request-trait.php
66 lines 2.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Trait WPCOM_REST_API_Proxy_Request_Trait
4 *
5 * Used to proxy requests to wpcom servers.
6 *
7 * @package automattic/jetpack
8 */
9
10 use Automattic\Jetpack\Connection\Client;
11 use Automattic\Jetpack\Status\Visitor;
12
13 trait WPCOM_REST_API_Proxy_Request_Trait {
14
15 /**
16 * Proxy request to wpcom servers for the site and user.
17 *
18 * @param WP_Rest_Request $request Request to proxy.
19 * @param string $path Path to append to the rest base.
20 *
21 * @return mixed|WP_Error Response from wpcom servers or an error.
22 */
23 public function proxy_request_to_wpcom_as_user( $request, $path = '' ) {
24 $blog_id = \Jetpack_Options::get_option( 'id' );
25 $path = '/sites/' . rawurldecode( $blog_id ) . rawurldecode( $this->rest_base ) . ( $path ? '/' . rawurldecode( $path ) : '' );
26 $query_params = $request->get_query_params();
27
28 /*
29 * A rest_route parameter can be added when using plain permalinks.
30 * It is not necessary to pass them to WordPress.com,
31 * and may even cause issues with some endpoints.
32 * Let's remove it.
33 */
34 if ( isset( $query_params['rest_route'] ) ) {
35 unset( $query_params['rest_route'] );
36 }
37 $api_url = add_query_arg( $query_params, $path );
38
39 $request_options = array(
40 'headers' => array(
41 'Content-Type' => 'application/json',
42 'X-Forwarded-For' => ( new Visitor() )->get_ip( true ),
43 ),
44 'method' => $request->get_method(),
45 );
46
47 $response = Client::wpcom_json_api_request_as_user( $api_url, $this->version, $request_options, $request->get_body(), $this->base_api_path );
48
49 if ( is_wp_error( $response ) ) {
50 return $response;
51 }
52
53 $response_status = wp_remote_retrieve_response_code( $response );
54 $response_body = json_decode( wp_remote_retrieve_body( $response ) );
55
56 if ( $response_status >= 400 ) {
57 $code = isset( $response_body->code ) ? $response_body->code : 'unknown_error';
58 $message = isset( $response_body->message ) ? $response_body->message : __( 'An unknown error occurred.', 'jetpack' );
59
60 return new WP_Error( $code, $message, array( 'status' => $response_status ) );
61 }
62
63 return $response_body;
64 }
65 }
66