WordPress 4.4.1
[autoinstalls/wordpress.git] / wp-includes / class-oembed.php
1 <?php
2 /**
3  * API for fetching the HTML to embed remote content based on a provided URL.
4  * Used internally by the {@link WP_Embed} class, but is designed to be generic.
5  *
6  * @link https://codex.wordpress.org/oEmbed oEmbed Codex Article
7  * @link http://oembed.com/ oEmbed Homepage
8  *
9  * @package WordPress
10  * @subpackage oEmbed
11  */
12
13 /**
14  * oEmbed class.
15  *
16  * @package WordPress
17  * @subpackage oEmbed
18  * @since 2.9.0
19  */
20 class WP_oEmbed {
21         public $providers = array();
22         /**
23          * @static
24          * @var array
25          */
26         public static $early_providers = array();
27
28         private $compat_methods = array( '_fetch_with_format', '_parse_json', '_parse_xml', '_parse_body' );
29
30         /**
31          * Constructor
32          *
33          * @since 2.9.0
34          */
35         public function __construct() {
36                 $host = urlencode( home_url() );
37                 $providers = array(
38                         '#http://((m|www)\.)?youtube\.com/watch.*#i'          => array( 'http://www.youtube.com/oembed',                             true  ),
39                         '#https://((m|www)\.)?youtube\.com/watch.*#i'         => array( 'http://www.youtube.com/oembed?scheme=https',                true  ),
40                         '#http://((m|www)\.)?youtube\.com/playlist.*#i'       => array( 'http://www.youtube.com/oembed',                             true  ),
41                         '#https://((m|www)\.)?youtube\.com/playlist.*#i'      => array( 'http://www.youtube.com/oembed?scheme=https',                true  ),
42                         '#http://youtu\.be/.*#i'                              => array( 'http://www.youtube.com/oembed',                             true  ),
43                         '#https://youtu\.be/.*#i'                             => array( 'http://www.youtube.com/oembed?scheme=https',                true  ),
44                         '#https?://(.+\.)?vimeo\.com/.*#i'                    => array( 'http://vimeo.com/api/oembed.{format}',                      true  ),
45                         '#https?://(www\.)?dailymotion\.com/.*#i'             => array( 'https://www.dailymotion.com/services/oembed',               true  ),
46                         'http://dai.ly/*'                                     => array( 'https://www.dailymotion.com/services/oembed',               false ),
47                         '#https?://(www\.)?flickr\.com/.*#i'                  => array( 'https://www.flickr.com/services/oembed/',                   true  ),
48                         '#https?://flic\.kr/.*#i'                             => array( 'https://www.flickr.com/services/oembed/',                   true  ),
49                         '#https?://(.+\.)?smugmug\.com/.*#i'                  => array( 'http://api.smugmug.com/services/oembed/',                   true  ),
50                         '#https?://(www\.)?hulu\.com/watch/.*#i'              => array( 'http://www.hulu.com/api/oembed.{format}',                   true  ),
51                         'http://i*.photobucket.com/albums/*'                  => array( 'http://api.photobucket.com/oembed',                         false ),
52                         'http://gi*.photobucket.com/groups/*'                 => array( 'http://api.photobucket.com/oembed',                         false ),
53                         '#https?://(www\.)?scribd\.com/doc/.*#i'              => array( 'http://www.scribd.com/services/oembed',                     true  ),
54                         '#https?://wordpress.tv/.*#i'                         => array( 'http://wordpress.tv/oembed/',                               true  ),
55                         '#https?://(.+\.)?polldaddy\.com/.*#i'                => array( 'https://polldaddy.com/oembed/',                             true  ),
56                         '#https?://poll\.fm/.*#i'                             => array( 'https://polldaddy.com/oembed/',                             true  ),
57                         '#https?://(www\.)?funnyordie\.com/videos/.*#i'       => array( 'http://www.funnyordie.com/oembed',                          true  ),
58                         '#https?://(www\.)?twitter\.com/.+?/status(es)?/.*#i' => array( 'https://api.twitter.com/1/statuses/oembed.{format}',        true  ),
59                         '#https?://vine.co/v/.*#i'                            => array( 'https://vine.co/oembed.{format}',                           true  ),
60                         '#https?://(www\.)?soundcloud\.com/.*#i'              => array( 'http://soundcloud.com/oembed',                              true  ),
61                         '#https?://(.+?\.)?slideshare\.net/.*#i'              => array( 'https://www.slideshare.net/api/oembed/2',                   true  ),
62                         '#https?://(www\.)?instagr(\.am|am\.com)/p/.*#i'      => array( 'https://api.instagram.com/oembed',                          true  ),
63                         '#https?://(open|play)\.spotify\.com/.*#i'            => array( 'https://embed.spotify.com/oembed/',                         true  ),
64                         '#https?://(.+\.)?imgur\.com/.*#i'                    => array( 'http://api.imgur.com/oembed',                               true  ),
65                         '#https?://(www\.)?meetu(\.ps|p\.com)/.*#i'           => array( 'http://api.meetup.com/oembed',                              true  ),
66                         '#https?://(www\.)?issuu\.com/.+/docs/.+#i'           => array( 'http://issuu.com/oembed_wp',                                true  ),
67                         '#https?://(www\.)?collegehumor\.com/video/.*#i'      => array( 'http://www.collegehumor.com/oembed.{format}',               true  ),
68                         '#https?://(www\.)?mixcloud\.com/.*#i'                => array( 'http://www.mixcloud.com/oembed',                            true  ),
69                         '#https?://(www\.|embed\.)?ted\.com/talks/.*#i'       => array( 'http://www.ted.com/talks/oembed.{format}',                  true  ),
70                         '#https?://(www\.)?(animoto|video214)\.com/play/.*#i' => array( 'https://animoto.com/oembeds/create',                        true  ),
71                         '#https?://(.+)\.tumblr\.com/post/.*#i'               => array( 'https://www.tumblr.com/oembed/1.0',                         true  ),
72                         '#https?://(www\.)?kickstarter\.com/projects/.*#i'    => array( 'https://www.kickstarter.com/services/oembed',               true  ),
73                         '#https?://kck\.st/.*#i'                              => array( 'https://www.kickstarter.com/services/oembed',               true  ),
74                         '#https?://cloudup\.com/.*#i'                         => array( 'https://cloudup.com/oembed',                                true  ),
75                         '#https?://(www\.)?reverbnation\.com/.*#i'            => array( 'https://www.reverbnation.com/oembed',                       true  ),
76                         '#https?://videopress.com/v/.*#'                      => array( 'https://public-api.wordpress.com/oembed/1.0/?for=' . $host, true  ),
77                         '#https?://(www\.)?reddit\.com/r/[^/]+/comments/.*#i' => array( 'https://www.reddit.com/oembed',                             true  ),
78                         '#https?://(www\.)?speakerdeck\.com/.*#i'             => array( 'https://speakerdeck.com/oembed.{format}',                   true  ),
79                 );
80
81                 if ( ! empty( self::$early_providers['add'] ) ) {
82                         foreach ( self::$early_providers['add'] as $format => $data ) {
83                                 $providers[ $format ] = $data;
84                         }
85                 }
86
87                 if ( ! empty( self::$early_providers['remove'] ) ) {
88                         foreach ( self::$early_providers['remove'] as $format ) {
89                                 unset( $providers[ $format ] );
90                         }
91                 }
92
93                 self::$early_providers = array();
94
95                 /**
96                  * Filter the list of whitelisted oEmbed providers.
97                  *
98                  * Since WordPress 4.4, oEmbed discovery is enabled for all users and allows embedding of sanitized
99                  * iframes. The providers in this list are whitelisted, meaning they are trusted and allowed to
100                  * embed any content, such as iframes, videos, JavaScript, and arbitrary HTML.
101                  *
102                  * Supported providers:
103                  *
104                  * |   Provider   |        Flavor        | HTTPS |   Since   |
105                  * | ------------ | -------------------- | :---: | --------- |
106                  * | Dailymotion  | dailymotion.com      |  Yes  | 2.9.0     |
107                  * | Flickr       | flickr.com           |  Yes  | 2.9.0     |
108                  * | Hulu         | hulu.com             |  Yes  | 2.9.0     |
109                  * | Photobucket  | photobucket.com      |  No   | 2.9.0     |
110                  * | Scribd       | scribd.com           |  Yes  | 2.9.0     |
111                  * | Vimeo        | vimeo.com            |  Yes  | 2.9.0     |
112                  * | WordPress.tv | wordpress.tv         |  Yes  | 2.9.0     |
113                  * | YouTube      | youtube.com/watch    |  Yes  | 2.9.0     |
114                  * | Funny or Die | funnyordie.com       |  Yes  | 3.0.0     |
115                  * | Polldaddy    | polldaddy.com        |  Yes  | 3.0.0     |
116                  * | SmugMug      | smugmug.com          |  Yes  | 3.0.0     |
117                  * | YouTube      | youtu.be             |  Yes  | 3.0.0     |
118                  * | Twitter      | twitter.com          |  Yes  | 3.4.0     |
119                  * | Instagram    | instagram.com        |  Yes  | 3.5.0     |
120                  * | Instagram    | instagr.am           |  Yes  | 3.5.0     |
121                  * | Slideshare   | slideshare.net       |  Yes  | 3.5.0     |
122                  * | SoundCloud   | soundcloud.com       |  Yes  | 3.5.0     |
123                  * | Dailymotion  | dai.ly               |  No   | 3.6.0     |
124                  * | Flickr       | flic.kr              |  Yes  | 3.6.0     |
125                  * | Spotify      | spotify.com          |  Yes  | 3.6.0     |
126                  * | Imgur        | imgur.com            |  Yes  | 3.9.0     |
127                  * | Meetup.com   | meetup.com           |  Yes  | 3.9.0     |
128                  * | Meetup.com   | meetu.ps             |  Yes  | 3.9.0     |
129                  * | Animoto      | animoto.com          |  Yes  | 4.0.0     |
130                  * | Animoto      | video214.com         |  Yes  | 4.0.0     |
131                  * | CollegeHumor | collegehumor.com     |  Yes  | 4.0.0     |
132                  * | Issuu        | issuu.com            |  Yes  | 4.0.0     |
133                  * | Mixcloud     | mixcloud.com         |  Yes  | 4.0.0     |
134                  * | Polldaddy    | poll.fm              |  Yes  | 4.0.0     |
135                  * | TED          | ted.com              |  Yes  | 4.0.0     |
136                  * | YouTube      | youtube.com/playlist |  Yes  | 4.0.0     |
137                  * | Vine         | vine.co              |  Yes  | 4.1.0     |
138                  * | Tumblr       | tumblr.com           |  Yes  | 4.2.0     |
139                  * | Kickstarter  | kickstarter.com      |  Yes  | 4.2.0     |
140                  * | Kickstarter  | kck.st               |  Yes  | 4.2.0     |
141                  * | Cloudup      | cloudup.com          |  Yes  | 4.4.0     |
142                  * | ReverbNation | reverbnation.com     |  Yes  | 4.4.0     |
143                  * | VideoPress   | videopress.com       |  Yes  | 4.4.0     |
144                  * | Reddit       | reddit.com           |  Yes  | 4.4.0     |
145                  * | Speaker Deck | speakerdeck.com      |  Yes  | 4.4.0     |
146                  *
147                  * No longer supported providers:
148                  *
149                  * |   Provider   |        Flavor        | HTTPS |   Since   |  Removed  |
150                  * | ------------ | -------------------- | :---: | --------- | --------- |
151                  * | Qik          | qik.com              |  Yes  | 2.9.0     | 3.9.0     |
152                  * | Viddler      | viddler.com          |  Yes  | 2.9.0     | 4.0.0     |
153                  * | Revision3    | revision3.com        |  No   | 2.9.0     | 4.2.0     |
154                  * | Blip         | blip.tv              |  No   | 2.9.0     | 4.4.0     |
155                  * | Rdio         | rdio.com             |  Yes  | 3.6.0     | 4.4.1     |
156                  * | Rdio         | rd.io                |  Yes  | 3.6.0     | 4.4.1     |
157                  *
158                  * @see wp_oembed_add_provider()
159                  *
160                  * @since 2.9.0
161                  *
162                  * @param array $providers An array of popular oEmbed providers.
163                  */
164                 $this->providers = apply_filters( 'oembed_providers', $providers );
165
166                 // Fix any embeds that contain new lines in the middle of the HTML which breaks wpautop().
167                 add_filter( 'oembed_dataparse', array($this, '_strip_newlines'), 10, 3 );
168         }
169
170         /**
171          * Make private/protected methods readable for backwards compatibility.
172          *
173          * @since 4.0.0
174          * @access public
175          *
176          * @param callable $name      Method to call.
177          * @param array    $arguments Arguments to pass when calling.
178          * @return mixed|bool Return value of the callback, false otherwise.
179          */
180         public function __call( $name, $arguments ) {
181                 if ( in_array( $name, $this->compat_methods ) ) {
182                         return call_user_func_array( array( $this, $name ), $arguments );
183                 }
184                 return false;
185         }
186
187         /**
188          * Takes a URL and returns the corresponding oEmbed provider's URL, if there is one.
189          *
190          * @since 4.0.0
191          * @access public
192          *
193          * @see WP_oEmbed::discover()
194          *
195          * @param string        $url  The URL to the content.
196          * @param string|array  $args Optional provider arguments.
197          * @return false|string False on failure, otherwise the oEmbed provider URL.
198          */
199         public function get_provider( $url, $args = '' ) {
200
201                 $provider = false;
202
203                 if ( !isset($args['discover']) )
204                         $args['discover'] = true;
205
206                 foreach ( $this->providers as $matchmask => $data ) {
207                         list( $providerurl, $regex ) = $data;
208
209                         // Turn the asterisk-type provider URLs into regex
210                         if ( !$regex ) {
211                                 $matchmask = '#' . str_replace( '___wildcard___', '(.+)', preg_quote( str_replace( '*', '___wildcard___', $matchmask ), '#' ) ) . '#i';
212                                 $matchmask = preg_replace( '|^#http\\\://|', '#https?\://', $matchmask );
213                         }
214
215                         if ( preg_match( $matchmask, $url ) ) {
216                                 $provider = str_replace( '{format}', 'json', $providerurl ); // JSON is easier to deal with than XML
217                                 break;
218                         }
219                 }
220
221                 if ( !$provider && $args['discover'] )
222                         $provider = $this->discover( $url );
223
224                 return $provider;
225         }
226
227         /**
228          * Add an oEmbed provider just-in-time when wp_oembed_add_provider() is called
229          * before the 'plugins_loaded' hook.
230          *
231          * The just-in-time addition is for the benefit of the 'oembed_providers' filter.
232          *
233          * @since 4.0.0
234          * @access public
235          * @static
236          *
237          * @see wp_oembed_add_provider()
238          *
239          * @param string $format   Format of URL that this provider can handle. You can use
240          *                         asterisks as wildcards.
241          * @param string $provider The URL to the oEmbed provider..
242          * @param bool   $regex    Optional. Whether the $format parameter is in a regex format.
243          *                         Default false.
244          */
245         public static function _add_provider_early( $format, $provider, $regex = false ) {
246                 if ( empty( self::$early_providers['add'] ) ) {
247                         self::$early_providers['add'] = array();
248                 }
249
250                 self::$early_providers['add'][ $format ] = array( $provider, $regex );
251         }
252
253         /**
254          * Remove an oEmbed provider just-in-time when wp_oembed_remove_provider() is called
255          * before the 'plugins_loaded' hook.
256          *
257          * The just-in-time removal is for the benefit of the 'oembed_providers' filter.
258          *
259          * @since 4.0.0
260          * @access public
261          * @static
262          *
263          * @see wp_oembed_remove_provider()
264          *
265          * @param string $format The format of URL that this provider can handle. You can use
266          *                       asterisks as wildcards.
267          */
268         public static function _remove_provider_early( $format ) {
269                 if ( empty( self::$early_providers['remove'] ) ) {
270                         self::$early_providers['remove'] = array();
271                 }
272
273                 self::$early_providers['remove'][] = $format;
274         }
275
276         /**
277          * The do-it-all function that takes a URL and attempts to return the HTML.
278          *
279          * @see WP_oEmbed::fetch()
280          * @see WP_oEmbed::data2html()
281          *
282          * @param string $url The URL to the content that should be attempted to be embedded.
283          * @param array $args Optional arguments. Usually passed from a shortcode.
284          * @return false|string False on failure, otherwise the UNSANITIZED (and potentially unsafe) HTML that should be used to embed.
285          */
286         public function get_html( $url, $args = '' ) {
287                 $provider = $this->get_provider( $url, $args );
288
289                 if ( !$provider || false === $data = $this->fetch( $provider, $url, $args ) )
290                         return false;
291
292                 /**
293                  * Filter the HTML returned by the oEmbed provider.
294                  *
295                  * @since 2.9.0
296                  *
297                  * @param string $data The returned oEmbed HTML.
298                  * @param string $url  URL of the content to be embedded.
299                  * @param array  $args Optional arguments, usually passed from a shortcode.
300                  */
301                 return apply_filters( 'oembed_result', $this->data2html( $data, $url ), $url, $args );
302         }
303
304         /**
305          * Attempts to discover link tags at the given URL for an oEmbed provider.
306          *
307          * @param string $url The URL that should be inspected for discovery `<link>` tags.
308          * @return false|string False on failure, otherwise the oEmbed provider URL.
309          */
310         public function discover( $url ) {
311                 $providers = array();
312
313                 /**
314                  * Filter oEmbed remote get arguments.
315                  *
316                  * @since 4.0.0
317                  *
318                  * @see WP_Http::request()
319                  *
320                  * @param array  $args oEmbed remote get arguments.
321                  * @param string $url  URL to be inspected.
322                  */
323                 $args = apply_filters( 'oembed_remote_get_args', array(), $url );
324
325                 // Fetch URL content
326                 $request = wp_safe_remote_get( $url, $args );
327                 if ( $html = wp_remote_retrieve_body( $request ) ) {
328
329                         /**
330                          * Filter the link types that contain oEmbed provider URLs.
331                          *
332                          * @since 2.9.0
333                          *
334                          * @param array $format Array of oEmbed link types. Accepts 'application/json+oembed',
335                          *                      'text/xml+oembed', and 'application/xml+oembed' (incorrect,
336                          *                      used by at least Vimeo).
337                          */
338                         $linktypes = apply_filters( 'oembed_linktypes', array(
339                                 'application/json+oembed' => 'json',
340                                 'text/xml+oembed' => 'xml',
341                                 'application/xml+oembed' => 'xml',
342                         ) );
343
344                         // Strip <body>
345                         $html = substr( $html, 0, stripos( $html, '</head>' ) );
346
347                         // Do a quick check
348                         $tagfound = false;
349                         foreach ( $linktypes as $linktype => $format ) {
350                                 if ( stripos($html, $linktype) ) {
351                                         $tagfound = true;
352                                         break;
353                                 }
354                         }
355
356                         if ( $tagfound && preg_match_all( '#<link([^<>]+)/?>#iU', $html, $links ) ) {
357                                 foreach ( $links[1] as $link ) {
358                                         $atts = shortcode_parse_atts( $link );
359
360                                         if ( !empty($atts['type']) && !empty($linktypes[$atts['type']]) && !empty($atts['href']) ) {
361                                                 $providers[$linktypes[$atts['type']]] = htmlspecialchars_decode( $atts['href'] );
362
363                                                 // Stop here if it's JSON (that's all we need)
364                                                 if ( 'json' == $linktypes[$atts['type']] )
365                                                         break;
366                                         }
367                                 }
368                         }
369                 }
370
371                 // JSON is preferred to XML
372                 if ( !empty($providers['json']) )
373                         return $providers['json'];
374                 elseif ( !empty($providers['xml']) )
375                         return $providers['xml'];
376                 else
377                         return false;
378         }
379
380         /**
381          * Connects to a oEmbed provider and returns the result.
382          *
383          * @param string $provider The URL to the oEmbed provider.
384          * @param string $url The URL to the content that is desired to be embedded.
385          * @param array $args Optional arguments. Usually passed from a shortcode.
386          * @return false|object False on failure, otherwise the result in the form of an object.
387          */
388         public function fetch( $provider, $url, $args = '' ) {
389                 $args = wp_parse_args( $args, wp_embed_defaults( $url ) );
390
391                 $provider = add_query_arg( 'maxwidth', (int) $args['width'], $provider );
392                 $provider = add_query_arg( 'maxheight', (int) $args['height'], $provider );
393                 $provider = add_query_arg( 'url', urlencode($url), $provider );
394
395                 /**
396                  * Filter the oEmbed URL to be fetched.
397                  *
398                  * @since 2.9.0
399                  *
400                  * @param string $provider URL of the oEmbed provider.
401                  * @param string $url      URL of the content to be embedded.
402                  * @param array  $args     Optional arguments, usually passed from a shortcode.
403                  */
404                 $provider = apply_filters( 'oembed_fetch_url', $provider, $url, $args );
405
406                 foreach ( array( 'json', 'xml' ) as $format ) {
407                         $result = $this->_fetch_with_format( $provider, $format );
408                         if ( is_wp_error( $result ) && 'not-implemented' == $result->get_error_code() )
409                                 continue;
410                         return ( $result && ! is_wp_error( $result ) ) ? $result : false;
411                 }
412                 return false;
413         }
414
415         /**
416          * Fetches result from an oEmbed provider for a specific format and complete provider URL
417          *
418          * @since 3.0.0
419          * @access private
420          * @param string $provider_url_with_args URL to the provider with full arguments list (url, maxheight, etc.)
421          * @param string $format Format to use
422          * @return false|object|WP_Error False on failure, otherwise the result in the form of an object.
423          */
424         private function _fetch_with_format( $provider_url_with_args, $format ) {
425                 $provider_url_with_args = add_query_arg( 'format', $format, $provider_url_with_args );
426
427                 /** This filter is documented in wp-includes/class-oembed.php */
428                 $args = apply_filters( 'oembed_remote_get_args', array(), $provider_url_with_args );
429
430                 $response = wp_safe_remote_get( $provider_url_with_args, $args );
431                 if ( 501 == wp_remote_retrieve_response_code( $response ) )
432                         return new WP_Error( 'not-implemented' );
433                 if ( ! $body = wp_remote_retrieve_body( $response ) )
434                         return false;
435                 $parse_method = "_parse_$format";
436                 return $this->$parse_method( $body );
437         }
438
439         /**
440          * Parses a json response body.
441          *
442          * @since 3.0.0
443          * @access private
444          *
445          * @param string $response_body
446          * @return object|false
447          */
448         private function _parse_json( $response_body ) {
449                 $data = json_decode( trim( $response_body ) );
450                 return ( $data && is_object( $data ) ) ? $data : false;
451         }
452
453         /**
454          * Parses an XML response body.
455          *
456          * @since 3.0.0
457          * @access private
458          *
459          * @param string $response_body
460          * @return object|false
461          */
462         private function _parse_xml( $response_body ) {
463                 if ( ! function_exists( 'libxml_disable_entity_loader' ) )
464                         return false;
465
466                 $loader = libxml_disable_entity_loader( true );
467                 $errors = libxml_use_internal_errors( true );
468
469                 $return = $this->_parse_xml_body( $response_body );
470
471                 libxml_use_internal_errors( $errors );
472                 libxml_disable_entity_loader( $loader );
473
474                 return $return;
475         }
476
477         /**
478          * Helper function for parsing an XML response body.
479          *
480          * @since 3.6.0
481          * @access private
482          *
483          * @param string $response_body
484          * @return object|false
485          */
486         private function _parse_xml_body( $response_body ) {
487                 if ( ! function_exists( 'simplexml_import_dom' ) || ! class_exists( 'DOMDocument', false ) )
488                         return false;
489
490                 $dom = new DOMDocument;
491                 $success = $dom->loadXML( $response_body );
492                 if ( ! $success )
493                         return false;
494
495                 if ( isset( $dom->doctype ) )
496                         return false;
497
498                 foreach ( $dom->childNodes as $child ) {
499                         if ( XML_DOCUMENT_TYPE_NODE === $child->nodeType )
500                                 return false;
501                 }
502
503                 $xml = simplexml_import_dom( $dom );
504                 if ( ! $xml )
505                         return false;
506
507                 $return = new stdClass;
508                 foreach ( $xml as $key => $value ) {
509                         $return->$key = (string) $value;
510                 }
511
512                 return $return;
513         }
514
515         /**
516          * Converts a data object from {@link WP_oEmbed::fetch()} and returns the HTML.
517          *
518          * @param object $data A data object result from an oEmbed provider.
519          * @param string $url The URL to the content that is desired to be embedded.
520          * @return false|string False on error, otherwise the HTML needed to embed.
521          */
522         public function data2html( $data, $url ) {
523                 if ( ! is_object( $data ) || empty( $data->type ) )
524                         return false;
525
526                 $return = false;
527
528                 switch ( $data->type ) {
529                         case 'photo':
530                                 if ( empty( $data->url ) || empty( $data->width ) || empty( $data->height ) )
531                                         break;
532                                 if ( ! is_string( $data->url ) || ! is_numeric( $data->width ) || ! is_numeric( $data->height ) )
533                                         break;
534
535                                 $title = ! empty( $data->title ) && is_string( $data->title ) ? $data->title : '';
536                                 $return = '<a href="' . esc_url( $url ) . '"><img src="' . esc_url( $data->url ) . '" alt="' . esc_attr($title) . '" width="' . esc_attr($data->width) . '" height="' . esc_attr($data->height) . '" /></a>';
537                                 break;
538
539                         case 'video':
540                         case 'rich':
541                                 if ( ! empty( $data->html ) && is_string( $data->html ) )
542                                         $return = $data->html;
543                                 break;
544
545                         case 'link':
546                                 if ( ! empty( $data->title ) && is_string( $data->title ) )
547                                         $return = '<a href="' . esc_url( $url ) . '">' . esc_html( $data->title ) . '</a>';
548                                 break;
549
550                         default:
551                                 $return = false;
552                 }
553
554                 /**
555                  * Filter the returned oEmbed HTML.
556                  *
557                  * Use this filter to add support for custom data types, or to filter the result.
558                  *
559                  * @since 2.9.0
560                  *
561                  * @param string $return The returned oEmbed HTML.
562                  * @param object $data   A data object result from an oEmbed provider.
563                  * @param string $url    The URL of the content to be embedded.
564                  */
565                 return apply_filters( 'oembed_dataparse', $return, $data, $url );
566         }
567
568         /**
569          * Strip any new lines from the HTML.
570          *
571          * @access public
572          * @param string $html Existing HTML.
573          * @param object $data Data object from WP_oEmbed::data2html()
574          * @param string $url The original URL passed to oEmbed.
575          * @return string Possibly modified $html
576          */
577         public function _strip_newlines( $html, $data, $url ) {
578                 if ( false === strpos( $html, "\n" ) ) {
579                         return $html;
580                 }
581
582                 $count = 1;
583                 $found = array();
584                 $token = '__PRE__';
585                 $search = array( "\t", "\n", "\r", ' ' );
586                 $replace = array( '__TAB__', '__NL__', '__CR__', '__SPACE__' );
587                 $tokenized = str_replace( $search, $replace, $html );
588
589                 preg_match_all( '#(<pre[^>]*>.+?</pre>)#i', $tokenized, $matches, PREG_SET_ORDER );
590                 foreach ( $matches as $i => $match ) {
591                         $tag_html = str_replace( $replace, $search, $match[0] );
592                         $tag_token = $token . $i;
593
594                         $found[ $tag_token ] = $tag_html;
595                         $html = str_replace( $tag_html, $tag_token, $html, $count );
596                 }
597
598                 $replaced = str_replace( $replace, $search, $html );
599                 $stripped = str_replace( array( "\r\n", "\n" ), '', $replaced );
600                 $pre = array_values( $found );
601                 $tokens = array_keys( $found );
602
603                 return str_replace( $tokens, $pre, $stripped );
604         }
605 }
606
607 /**
608  * Returns the initialized {@link WP_oEmbed} object
609  *
610  * @since 2.9.0
611  * @access private
612  *
613  * @staticvar WP_oEmbed $wp_oembed
614  *
615  * @return WP_oEmbed object.
616  */
617 function _wp_oembed_get_object() {
618         static $wp_oembed = null;
619
620         if ( is_null( $wp_oembed ) ) {
621                 $wp_oembed = new WP_oEmbed();
622         }
623         return $wp_oembed;
624 }