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