diff --git a/src/wp-includes/class-oembed.php b/src/wp-includes/class-oembed.php
index c25b8cbac8..24ee215653 100644
--- a/src/wp-includes/class-oembed.php
+++ b/src/wp-includes/class-oembed.php
@@ -318,6 +318,36 @@ class WP_oEmbed {
self::$early_providers['remove'][] = $format;
}
+ /**
+ * Takes a URL and attempts to return the oEmbed data.
+ *
+ * @see WP_oEmbed::fetch()
+ *
+ * @since 4.8.0
+ * @access public
+ *
+ * @param string $url The URL to the content that should be attempted to be embedded.
+ * @param array|string $args Optional. Arguments, usually passed from a shortcode. Default empty.
+ * @return false|object False on failure, otherwise the result in the form of an object.
+ */
+ public function get_data( $url, $args = '' ) {
+ $args = wp_parse_args( $args );
+
+ $provider = $this->get_provider( $url, $args );
+
+ if ( ! $provider ) {
+ return false;
+ }
+
+ $data = $this->fetch( $provider, $url, $args );
+
+ if ( false === $data ) {
+ return false;
+ }
+
+ return $data;
+ }
+
/**
* The do-it-all function that takes a URL and attempts to return the HTML.
*
@@ -332,8 +362,6 @@ class WP_oEmbed {
* @return false|string False on failure, otherwise the UNSANITIZED (and potentially unsafe) HTML that should be used to embed.
*/
public function get_html( $url, $args = '' ) {
- $args = wp_parse_args( $args );
-
/**
* Filters the oEmbed result before any HTTP requests are made.
*
@@ -355,9 +383,9 @@ class WP_oEmbed {
return $pre;
}
- $provider = $this->get_provider( $url, $args );
+ $data = $this->get_data( $url, $args );
- if ( ! $provider || false === $data = $this->fetch( $provider, $url, $args ) ) {
+ if ( false === $data ) {
return false;
}
diff --git a/src/wp-includes/class-wp-oembed-controller.php b/src/wp-includes/class-wp-oembed-controller.php
index 13fed836e6..d825c415d2 100644
--- a/src/wp-includes/class-wp-oembed-controller.php
+++ b/src/wp-includes/class-wp-oembed-controller.php
@@ -52,10 +52,51 @@ final class WP_oEmbed_Controller {
),
),
) );
+
+ register_rest_route( 'oembed/1.0', '/proxy', array(
+ array(
+ 'methods' => WP_REST_Server::READABLE,
+ 'callback' => array( $this, 'get_proxy_item' ),
+ 'permission_callback' => array( $this, 'get_proxy_item_permissions_check' ),
+ 'args' => array(
+ 'url' => array(
+ 'description' => __( 'The URL of the resource for which to fetch oEmbed data.' ),
+ 'type' => 'string',
+ 'required' => true,
+ 'sanitize_callback' => 'esc_url_raw',
+ ),
+ 'format' => array(
+ 'description' => __( 'The oEmbed format to use.' ),
+ 'type' => 'string',
+ 'default' => 'json',
+ 'enum' => array(
+ 'json',
+ 'xml',
+ ),
+ ),
+ 'maxwidth' => array(
+ 'description' => __( 'The maximum width of the embed frame in pixels.' ),
+ 'type' => 'integer',
+ 'default' => $maxwidth,
+ 'sanitize_callback' => 'absint',
+ ),
+ 'maxheight' => array(
+ 'description' => __( 'The maximum height of the embed frame in pixels.' ),
+ 'type' => 'integer',
+ 'sanitize_callback' => 'absint',
+ ),
+ 'discover' => array(
+ 'description' => __( 'Whether to perform an oEmbed discovery request for non-whitelisted providers.' ),
+ 'type' => 'boolean',
+ 'default' => true,
+ ),
+ ),
+ ),
+ ) );
}
/**
- * Callback for the API endpoint.
+ * Callback for the embed API endpoint.
*
* Returns the JSON object for the post.
*
@@ -86,4 +127,69 @@ final class WP_oEmbed_Controller {
return $data;
}
+
+ /**
+ * Checks if current user can make a proxy oEmbed request.
+ *
+ * @since 4.8.0
+ * @access public
+ *
+ * @return true|WP_Error True if the request has read access, WP_Error object otherwise.
+ */
+ public function get_proxy_item_permissions_check() {
+ if ( ! current_user_can( 'edit_posts' ) ) {
+ return new WP_Error( 'rest_forbidden', __( 'Sorry, you are not allowed to make proxied oEmbed requests.' ), array( 'status' => rest_authorization_required_code() ) );
+ }
+ return true;
+ }
+
+ /**
+ * Callback for the proxy API endpoint.
+ *
+ * Returns the JSON object for the proxied item.
+ *
+ * @since 4.8.0
+ * @access public
+ *
+ * @see WP_oEmbed::get_html()
+ * @param WP_REST_Request $request Full data about the request.
+ * @return WP_Error|array oEmbed response data or WP_Error on failure.
+ */
+ public function get_proxy_item( $request ) {
+ $args = $request->get_params();
+
+ // Serve oEmbed data from cache if set.
+ $cache_key = 'oembed_' . md5( serialize( $args ) );
+ $data = get_transient( $cache_key );
+ if ( ! empty( $data ) ) {
+ return $data;
+ }
+
+ $url = $request['url'];
+ unset( $args['url'] );
+
+ $data = _wp_oembed_get_object()->get_data( $url, $args );
+
+ if ( false === $data ) {
+ return new WP_Error( 'oembed_invalid_url', get_status_header_desc( 404 ), array( 'status' => 404 ) );
+ }
+
+ /**
+ * Filters the oEmbed TTL value (time to live).
+ *
+ * Similar to the {@see 'oembed_ttl'} filter, but for the REST API
+ * oEmbed proxy endpoint.
+ *
+ * @since 4.8.0
+ *
+ * @param int $time Time to live (in seconds).
+ * @param string $url The attempted embed URL.
+ * @param array $args An array of embed request arguments.
+ */
+ $ttl = apply_filters( 'rest_oembed_ttl', DAY_IN_SECONDS, $url, $args );
+
+ set_transient( $cache_key, $data, $ttl );
+
+ return $data;
+ }
}
diff --git a/src/wp-includes/js/media-views.js b/src/wp-includes/js/media-views.js
index b2fc9a5ee6..1bdc6e6575 100644
--- a/src/wp-includes/js/media-views.js
+++ b/src/wp-includes/js/media-views.js
@@ -4624,7 +4624,6 @@ EmbedLink = wp.media.view.Settings.extend({
}, wp.media.controller.Embed.sensitivity ),
fetch: function() {
- var embed;
// check if they haven't typed in 500 ms
if ( $('#embed-url-field').val() !== this.model.get('url') ) {
@@ -4635,23 +4634,25 @@ EmbedLink = wp.media.view.Settings.extend({
this.dfd.abort();
}
- embed = new wp.shortcode({
- tag: 'embed',
- attrs: _.pick( this.model.attributes, [ 'width', 'height', 'src' ] ),
- content: this.model.get('url')
- });
-
this.dfd = $.ajax({
- type: 'POST',
- url: wp.ajax.settings.url,
- context: this,
- data: {
- action: 'parse-embed',
- post_ID: wp.media.view.settings.post.id,
- shortcode: embed.string()
- }
+ url: wp.media.view.settings.oEmbedProxyUrl,
+ data: {
+ url: this.model.get( 'url' ),
+ maxwidth: this.model.get( 'width' ),
+ maxheight: this.model.get( 'height' ),
+ _wpnonce: wp.media.view.settings.nonce.wpRestApi
+ },
+ type: 'GET',
+ dataType: 'json',
+ context: this
})
- .done( this.renderoEmbed )
+ .done( function( response ) {
+ this.renderoEmbed( {
+ data: {
+ body: response.html || ''
+ }
+ } );
+ } )
.fail( this.renderFail );
},
diff --git a/src/wp-includes/js/media/views/embed/link.js b/src/wp-includes/js/media/views/embed/link.js
index 86aa5c83a9..1af96cfa5d 100644
--- a/src/wp-includes/js/media/views/embed/link.js
+++ b/src/wp-includes/js/media/views/embed/link.js
@@ -35,7 +35,6 @@ EmbedLink = wp.media.view.Settings.extend({
}, wp.media.controller.Embed.sensitivity ),
fetch: function() {
- var embed;
// check if they haven't typed in 500 ms
if ( $('#embed-url-field').val() !== this.model.get('url') ) {
@@ -46,23 +45,25 @@ EmbedLink = wp.media.view.Settings.extend({
this.dfd.abort();
}
- embed = new wp.shortcode({
- tag: 'embed',
- attrs: _.pick( this.model.attributes, [ 'width', 'height', 'src' ] ),
- content: this.model.get('url')
- });
-
this.dfd = $.ajax({
- type: 'POST',
- url: wp.ajax.settings.url,
- context: this,
- data: {
- action: 'parse-embed',
- post_ID: wp.media.view.settings.post.id,
- shortcode: embed.string()
- }
+ url: wp.media.view.settings.oEmbedProxyUrl,
+ data: {
+ url: this.model.get( 'url' ),
+ maxwidth: this.model.get( 'width' ),
+ maxheight: this.model.get( 'height' ),
+ _wpnonce: wp.media.view.settings.nonce.wpRestApi
+ },
+ type: 'GET',
+ dataType: 'json',
+ context: this
})
- .done( this.renderoEmbed )
+ .done( function( response ) {
+ this.renderoEmbed( {
+ data: {
+ body: response.html || ''
+ }
+ } );
+ } )
.fail( this.renderFail );
},
diff --git a/src/wp-includes/media.php b/src/wp-includes/media.php
index 65cf4c7aae..1092aaea97 100644
--- a/src/wp-includes/media.php
+++ b/src/wp-includes/media.php
@@ -3414,6 +3414,7 @@ function wp_enqueue_media( $args = array() ) {
'captions' => ! apply_filters( 'disable_captions', '' ),
'nonce' => array(
'sendToEditor' => wp_create_nonce( 'media-send-to-editor' ),
+ 'wpRestApi' => wp_create_nonce( 'wp_rest' ),
),
'post' => array(
'id' => 0,
@@ -3423,6 +3424,7 @@ function wp_enqueue_media( $args = array() ) {
'audio' => ( $show_audio_playlist ) ? 1 : 0,
'video' => ( $show_video_playlist ) ? 1 : 0,
),
+ 'oEmbedProxyUrl' => rest_url( 'oembed/1.0/proxy' ),
'embedExts' => $exts,
'embedMimes' => $ext_mimes,
'contentWidth' => $content_width,
diff --git a/tests/phpunit/tests/oembed/controller.php b/tests/phpunit/tests/oembed/controller.php
index de41b0d058..a23c799e41 100644
--- a/tests/phpunit/tests/oembed/controller.php
+++ b/tests/phpunit/tests/oembed/controller.php
@@ -9,6 +9,25 @@ class Test_oEmbed_Controller extends WP_UnitTestCase {
* @var WP_REST_Server
*/
protected $server;
+ protected static $editor;
+ protected static $subscriber;
+ const YOUTUBE_VIDEO_ID = 'OQSNhk5ICTI';
+ const INVALID_OEMBED_URL = 'https://www.notreallyanoembedprovider.com/watch?v=awesome-cat-video';
+
+ public static function wpSetUpBeforeClass( $factory ) {
+ self::$subscriber = $factory->user->create( array(
+ 'role' => 'subscriber',
+ ) );
+ self::$editor = $factory->user->create( array(
+ 'role' => 'editor',
+ 'user_email' => 'editor@example.com',
+ ) );
+ }
+
+ public static function wpTearDownAfterClass() {
+ self::delete_user( self::$subscriber );
+ self::delete_user( self::$editor );
+ }
public function setUp() {
parent::setUp();
@@ -18,6 +37,66 @@ class Test_oEmbed_Controller extends WP_UnitTestCase {
$this->server = $wp_rest_server = new Spy_REST_Server();
do_action( 'rest_api_init', $this->server );
+ add_filter( 'pre_http_request', array( $this, 'mock_embed_request' ), 10, 3 );
+ $this->request_count = 0;
+ }
+
+ public function tearDown() {
+ parent::tearDown();
+
+ remove_filter( 'pre_http_request', array( $this, 'mock_embed_request' ), 10, 3 );
+ }
+
+ /**
+ * Count of the number of requests attempted.
+ *
+ * @var int
+ */
+ public $request_count = 0;
+
+ /**
+ * Intercept oEmbed requests and mock responses.
+ *
+ * @param mixed $preempt Whether to preempt an HTTP request's return value. Default false.
+ * @param mixed $r HTTP request arguments.
+ * @param string $url The request URL.
+ * @return array Response data.
+ */
+ public function mock_embed_request( $preempt, $r, $url ) {
+ unset( $preempt, $r );
+
+ $this->request_count += 1;
+
+ // Mock request to YouTube Embed.
+ if ( false !== strpos( $url, self::YOUTUBE_VIDEO_ID ) ) {
+ return array(
+ 'response' => array(
+ 'code' => 200,
+ ),
+ 'body' => wp_json_encode(
+ array(
+ 'version' => '1.0',
+ 'type' => 'video',
+ 'provider_name' => 'YouTube',
+ 'provider_url' => 'https://www.youtube.com',
+ 'thumbnail_width' => 480,
+ 'width' => 500,
+ 'thumbnail_height' => 360,
+ 'html' => '',
+ 'author_name' => 'Yosemitebear62',
+ 'thumbnail_url' => 'https://i.ytimg.com/vi/' . self::YOUTUBE_VIDEO_ID . '/hqdefault.jpg',
+ 'title' => 'Yosemitebear Mountain Double Rainbow 1-8-10',
+ 'height' => 375,
+ )
+ ),
+ );
+ } else {
+ return array(
+ 'response' => array(
+ 'code' => 404,
+ ),
+ );
+ }
}
function test_wp_oembed_ensure_format() {
@@ -86,6 +165,15 @@ class Test_oEmbed_Controller extends WP_UnitTestCase {
$this->assertArrayHasKey( 'callback', $route[0] );
$this->assertArrayHasKey( 'methods', $route[0] );
$this->assertArrayHasKey( 'args', $route[0] );
+
+ // Check proxy route registration.
+ $this->assertArrayHasKey( '/oembed/1.0/proxy', $filtered_routes );
+ $proxy_route = $filtered_routes['/oembed/1.0/proxy'];
+ $this->assertCount( 1, $proxy_route );
+ $this->assertArrayHasKey( 'callback', $proxy_route[0] );
+ $this->assertArrayHasKey( 'permission_callback', $proxy_route[0] );
+ $this->assertArrayHasKey( 'methods', $proxy_route[0] );
+ $this->assertArrayHasKey( 'args', $proxy_route[0] );
}
function test_request_with_wrong_method() {
@@ -348,4 +436,100 @@ class Test_oEmbed_Controller extends WP_UnitTestCase {
update_option( 'permalink_structure', '' );
}
+
+ public function test_proxy_without_permission() {
+ // Test without a login.
+ $request = new WP_REST_Request( 'GET', '/oembed/1.0/proxy' );
+ $response = $this->server->dispatch( $request );
+
+ $this->assertEquals( 400, $response->get_status() );
+
+ // Test with a user that does not have edit_posts capability.
+ wp_set_current_user( self::$subscriber );
+ $request = new WP_REST_Request( 'GET', '/oembed/1.0/proxy' );
+ $request->set_param( 'url', self::INVALID_OEMBED_URL );
+ $response = $this->server->dispatch( $request );
+
+ $this->assertEquals( 403, $response->get_status() );
+ $data = $response->get_data();
+ $this->assertEquals( $data['code'], 'rest_forbidden' );
+ }
+
+ public function test_proxy_with_invalid_oembed_provider() {
+ wp_set_current_user( self::$editor );
+ $request = new WP_REST_Request( 'GET', '/oembed/1.0/proxy' );
+ $request->set_param( 'url', self::INVALID_OEMBED_URL );
+ $response = $this->server->dispatch( $request );
+ $this->assertEquals( 404, $response->get_status() );
+ $data = $response->get_data();
+ $this->assertEquals( 'oembed_invalid_url', $data['code'] );
+ }
+
+ public function test_proxy_with_invalid_type() {
+ wp_set_current_user( self::$editor );
+ $request = new WP_REST_Request( 'GET', '/oembed/1.0/proxy' );
+ $request->set_param( 'type', 'xml' );
+ $response = $this->server->dispatch( $request );
+
+ $this->assertEquals( 400, $response->get_status() );
+ $data = $response->get_data();
+ }
+
+ public function test_proxy_with_valid_oembed_provider() {
+ wp_set_current_user( self::$editor );
+
+ $request = new WP_REST_Request( 'GET', '/oembed/1.0/proxy' );
+ $request->set_param( 'url', 'https://www.youtube.com/watch?v=' . self::YOUTUBE_VIDEO_ID );
+ $response = $this->server->dispatch( $request );
+ $this->assertEquals( 200, $response->get_status() );
+ $this->assertEquals( 1, $this->request_count );
+
+ // Subsequent request is cached and so it should not cause a request.
+ $response = $this->server->dispatch( $request );
+ $this->assertEquals( 1, $this->request_count );
+
+ // Test data object.
+ $data = $response->get_data();
+
+ $this->assertNotEmpty( $data );
+ $this->assertTrue( is_object( $data ) );
+ $this->assertEquals( 'YouTube', $data->provider_name );
+ $this->assertEquals( 'https://i.ytimg.com/vi/' . self::YOUTUBE_VIDEO_ID . '/hqdefault.jpg', $data->thumbnail_url );
+ }
+
+ public function test_proxy_with_invalid_oembed_provider_no_discovery() {
+ wp_set_current_user( self::$editor );
+
+ // If discover is false for an unkown provider, no discovery request should take place.
+ $request = new WP_REST_Request( 'GET', '/oembed/1.0/proxy' );
+ $request->set_param( 'url', self::INVALID_OEMBED_URL );
+ $request->set_param( 'discover', 0 );
+ $response = $this->server->dispatch( $request );
+ $this->assertEquals( 404, $response->get_status() );
+ $this->assertEquals( 0, $this->request_count );
+ }
+
+ public function test_proxy_with_invalid_oembed_provider_with_default_discover_param() {
+ wp_set_current_user( self::$editor );
+
+ // For an unkown provider, a discovery request should happen.
+ $request = new WP_REST_Request( 'GET', '/oembed/1.0/proxy' );
+ $request->set_param( 'url', self::INVALID_OEMBED_URL );
+ $response = $this->server->dispatch( $request );
+ $this->assertEquals( 404, $response->get_status() );
+ $this->assertEquals( 1, $this->request_count );
+ }
+
+ public function test_proxy_with_invalid_discover_param() {
+ wp_set_current_user( self::$editor );
+ $request = new WP_REST_Request( 'GET', '/oembed/1.0/proxy' );
+ $request->set_param( 'url', self::INVALID_OEMBED_URL );
+ $request->set_param( 'discover', 'notaboolean' );
+
+ $response = $this->server->dispatch( $request );
+
+ $this->assertEquals( 400, $response->get_status() );
+ $data = $response->get_data();
+ $this->assertEquals( $data['code'], 'rest_invalid_param' );
+ }
}
diff --git a/tests/phpunit/tests/rest-api/rest-schema-setup.php b/tests/phpunit/tests/rest-api/rest-schema-setup.php
index 360a075c8e..0c862552fe 100644
--- a/tests/phpunit/tests/rest-api/rest-schema-setup.php
+++ b/tests/phpunit/tests/rest-api/rest-schema-setup.php
@@ -43,6 +43,7 @@ class WP_Test_REST_Schema_Initialization extends WP_Test_REST_TestCase {
'/',
'/oembed/1.0',
'/oembed/1.0/embed',
+ '/oembed/1.0/proxy',
'/wp/v2',
'/wp/v2/posts',
'/wp/v2/posts/(?P[\\d]+)',
@@ -165,6 +166,10 @@ class WP_Test_REST_Schema_Initialization extends WP_Test_REST_TestCase {
'route' => '/oembed/1.0/embed',
'name' => 'oembeds',
),
+ array(
+ 'route' => '/oembed/1.0/proxy',
+ 'name' => 'oembedProxy',
+ ),
array(
'route' => '/wp/v2/posts',
'name' => 'PostsCollection',
diff --git a/tests/qunit/fixtures/wp-api-generated.js b/tests/qunit/fixtures/wp-api-generated.js
index 3f1f304f5e..140472dcf9 100644
--- a/tests/qunit/fixtures/wp-api-generated.js
+++ b/tests/qunit/fixtures/wp-api-generated.js
@@ -95,6 +95,56 @@ mockedApiResponse.Schema = {
"self": "http://example.org/?rest_route=/oembed/1.0/embed"
}
},
+ "/oembed/1.0/proxy": {
+ "namespace": "oembed/1.0",
+ "methods": [
+ "GET"
+ ],
+ "endpoints": [
+ {
+ "methods": [
+ "GET"
+ ],
+ "args": {
+ "url": {
+ "required": true,
+ "description": "The URL of the resource for which to fetch oEmbed data.",
+ "type": "string"
+ },
+ "format": {
+ "required": false,
+ "default": "json",
+ "enum": [
+ "json",
+ "xml"
+ ],
+ "description": "The oEmbed format to use.",
+ "type": "string"
+ },
+ "maxwidth": {
+ "required": false,
+ "default": 600,
+ "description": "The maximum width of the embed frame in pixels.",
+ "type": "integer"
+ },
+ "maxheight": {
+ "required": false,
+ "description": "The maximum height of the embed frame in pixels.",
+ "type": "integer"
+ },
+ "discover": {
+ "required": false,
+ "default": true,
+ "description": "Whether to perform an oEmbed discovery request for non-whitelisted providers.",
+ "type": "boolean"
+ }
+ }
+ }
+ ],
+ "_links": {
+ "self": "http://example.org/?rest_route=/oembed/1.0/proxy"
+ }
+ },
"/wp/v2": {
"namespace": "wp/v2",
"methods": [
@@ -3396,6 +3446,56 @@ mockedApiResponse.oembed = {
"_links": {
"self": "http://example.org/?rest_route=/oembed/1.0/embed"
}
+ },
+ "/oembed/1.0/proxy": {
+ "namespace": "oembed/1.0",
+ "methods": [
+ "GET"
+ ],
+ "endpoints": [
+ {
+ "methods": [
+ "GET"
+ ],
+ "args": {
+ "url": {
+ "required": true,
+ "description": "The URL of the resource for which to fetch oEmbed data.",
+ "type": "string"
+ },
+ "format": {
+ "required": false,
+ "default": "json",
+ "enum": [
+ "json",
+ "xml"
+ ],
+ "description": "The oEmbed format to use.",
+ "type": "string"
+ },
+ "maxwidth": {
+ "required": false,
+ "default": 600,
+ "description": "The maximum width of the embed frame in pixels.",
+ "type": "integer"
+ },
+ "maxheight": {
+ "required": false,
+ "description": "The maximum height of the embed frame in pixels.",
+ "type": "integer"
+ },
+ "discover": {
+ "required": false,
+ "default": true,
+ "description": "Whether to perform an oEmbed discovery request for non-whitelisted providers.",
+ "type": "boolean"
+ }
+ }
+ }
+ ],
+ "_links": {
+ "self": "http://example.org/?rest_route=/oembed/1.0/proxy"
+ }
}
}
};
@@ -3411,6 +3511,17 @@ mockedApiResponse.oembeds = {
}
};
+mockedApiResponse.oembedProxy = {
+ "code": "rest_missing_callback_param",
+ "message": "Missing parameter(s): url",
+ "data": {
+ "status": 400,
+ "params": [
+ "url"
+ ]
+ }
+};
+
mockedApiResponse.PostsCollection = [
{
"id": 3,