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