'application/json', 'User-Agent' => 'Ojelio-WordPress/' . OJELIO_VERSION . '; ' . home_url(), ), isset( $args['headers'] ) ? $args['headers'] : array() ); if ( ! empty( $args['token'] ) ) { $headers['Authorization'] = 'Bearer ' . $args['token']; } $request = array( 'method' => $method, 'headers' => $headers, 'timeout' => isset( $args['timeout'] ) ? $args['timeout'] : 20, ); if ( array_key_exists( 'body', $args ) ) { $request['headers']['Content-Type'] = 'application/json'; $request['body'] = wp_json_encode( $args['body'] ); } // Not wp_safe_remote_request(): the address is Ojelio's own, and a test // server on this computer (OJELIO_URL) must be reachable. $response = wp_remote_request( untrailingslashit( OJELIO_URL ) . '/api/v1' . $path, $request ); if ( is_wp_error( $response ) ) { return new WP_Error( 'ojelio_unreachable', /* translators: %s: the reason the request failed, from WordPress. */ sprintf( __( 'Could not reach Ojelio: %s', 'ojelio' ), $response->get_error_message() ) ); } $status = (int) wp_remote_retrieve_response_code( $response ); $body = json_decode( wp_remote_retrieve_body( $response ), true ); if ( $status >= 200 && $status < 300 ) { return is_array( $body ) ? $body : array(); } $error = is_array( $body ) && isset( $body['error'] ) && is_array( $body['error'] ) ? $body['error'] : array(); $code = isset( $error['code'] ) ? sanitize_key( $error['code'] ) : 'internal'; $data = array( 'status' => $status ); if ( isset( $error['field'] ) ) { $data['field'] = $error['field']; } $retry = wp_remote_retrieve_header( $response, 'retry-after' ); if ( $retry ) { $data['retry_after'] = (int) $retry; } return new WP_Error( 'ojelio_' . $code, isset( $error['message'] ) ? $error['message'] : __( 'Ojelio answered with an error. Try again in a moment.', 'ojelio' ), $data ); } /** An address on Ojelio, for links shown to people. */ public static function app_url( $path = '' ) { return untrailingslashit( OJELIO_URL ) . $path; } }