$method, // A settings page shouldn't hang on a slow network: reads give up sooner than sends. 'timeout' => 'GET' === $method ? 10 : 20, 'headers' => array( 'Accept' => 'application/json', 'User-Agent' => 'LeeloWordPress/' . LEELO_VERSION . '; ' . home_url( '/' ), ), ); if ( $keyed ) { $key = (string) Leelo_Settings::get( 'key' ); if ( '' === $key ) { return new WP_Error( 'leelo_not_connected', __( 'Connect this site to Leelo first.', 'leelo' ) ); } $args['headers']['Authorization'] = 'Bearer ' . $key; } if ( null !== $body ) { $args['headers']['Content-Type'] = 'application/json'; $args['body'] = wp_json_encode( $body ); } $response = wp_remote_request( LEELO_API . $path, $args ); if ( is_wp_error( $response ) ) { return new WP_Error( 'leelo_unreachable', __( 'Leelo could not be reached. Please try again in a moment.', 'leelo' ) ); } $status = (int) wp_remote_retrieve_response_code( $response ); $data = json_decode( wp_remote_retrieve_body( $response ), true ); if ( $status >= 400 ) { $code = isset( $data['error']['code'] ) ? (string) $data['error']['code'] : 'leelo_http_' . $status; $message = isset( $data['error']['message'] ) ? (string) $data['error']['message'] : sprintf( /* translators: %d: HTTP status code */ __( 'Leelo answered with an error (%d).', 'leelo' ), $status ); // A key that stopped working (revoked, or the site was removed at Leelo): forget it. if ( 401 === $status && $keyed ) { Leelo_Settings::update( array( 'key' => '' ) ); } return new WP_Error( $code, $message, array( 'status' => $status ) ); } return is_array( $data ) ? $data : array(); } public static function get( $path ) { return self::request( 'GET', $path ); } public static function post( $path, array $body ) { return self::request( 'POST', $path, $body ); } public static function delete( $path ) { return self::request( 'DELETE', $path ); } }