]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/class-oembed.php
Wordpress 3.5.2-scripts
[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 http://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         var $providers = array();
22
23         /**
24          * Constructor
25          *
26          * @uses apply_filters() Filters a list of pre-defined oEmbed providers.
27          */
28         function __construct() {
29                 // List out some popular sites that support oEmbed.
30                 // The WP_Embed class disables discovery for non-unfiltered_html users, so only providers in this array will be used for them.
31                 // Add to this list using the wp_oembed_add_provider() function (see its PHPDoc for details).
32                 $this->providers = apply_filters( 'oembed_providers', array(
33                         '#https?://(www\.)?youtube.com/watch.*#i'            => array( 'http://www.youtube.com/oembed',                     true  ),
34                         'http://youtu.be/*'                                  => array( 'http://www.youtube.com/oembed',                     false ),
35                         'http://blip.tv/*'                                   => array( 'http://blip.tv/oembed/',                            false ),
36                         '#https?://(www\.)?vimeo\.com/.*#i'                  => array( 'http://vimeo.com/api/oembed.{format}',              true  ),
37                         '#https?://(www\.)?dailymotion\.com/.*#i'            => array( 'http://www.dailymotion.com/services/oembed',        true  ),
38                         '#https?://(www\.)?flickr\.com/.*#i'                 => array( 'http://www.flickr.com/services/oembed/',            true  ),
39                         '#https?://(.+\.)?smugmug\.com/.*#i'                 => array( 'http://api.smugmug.com/services/oembed/',           true  ),
40                         '#https?://(www\.)?hulu\.com/watch/.*#i'             => array( 'http://www.hulu.com/api/oembed.{format}',           true  ),
41                         '#https?://(www\.)?viddler\.com/.*#i'                => array( 'http://lab.viddler.com/services/oembed/',           true  ),
42                         'http://qik.com/*'                                   => array( 'http://qik.com/api/oembed.{format}',                false ),
43                         'http://revision3.com/*'                             => array( 'http://revision3.com/api/oembed/',                  false ),
44                         'http://i*.photobucket.com/albums/*'                 => array( 'http://photobucket.com/oembed',                     false ),
45                         'http://gi*.photobucket.com/groups/*'                => array( 'http://photobucket.com/oembed',                     false ),
46                         '#https?://(www\.)?scribd\.com/.*#i'                 => array( 'http://www.scribd.com/services/oembed',             true  ),
47                         'http://wordpress.tv/*'                              => array( 'http://wordpress.tv/oembed/',                       false ),
48                         '#https?://(.+\.)?polldaddy\.com/.*#i'               => array( 'http://polldaddy.com/oembed/',                      true  ),
49                         '#https?://(www\.)?funnyordie\.com/videos/.*#i'      => array( 'http://www.funnyordie.com/oembed',                  true  ),
50                         '#https?://(www\.)?twitter.com/.+?/status(es)?/.*#i' => array( 'http://api.twitter.com/1/statuses/oembed.{format}', true  ),
51                         '#https?://(www\.)?soundcloud\.com/.*#i'             => array( 'http://soundcloud.com/oembed',                      true  ),
52                         '#https?://(www\.)?slideshare.net/*#'                => array( 'http://www.slideshare.net/api/oembed/2',            true  ),
53                         '#http://instagr(\.am|am\.com)/p/.*#i'               => array( 'http://api.instagram.com/oembed',                   true  ),
54                 ) );
55
56                 // Fix any embeds that contain new lines in the middle of the HTML which breaks wpautop().
57                 add_filter( 'oembed_dataparse', array($this, '_strip_newlines'), 10, 3 );
58         }
59
60         /**
61          * The do-it-all function that takes a URL and attempts to return the HTML.
62          *
63          * @see WP_oEmbed::discover()
64          * @see WP_oEmbed::fetch()
65          * @see WP_oEmbed::data2html()
66          *
67          * @param string $url The URL to the content that should be attempted to be embedded.
68          * @param array $args Optional arguments. Usually passed from a shortcode.
69          * @return bool|string False on failure, otherwise the UNSANITIZED (and potentially unsafe) HTML that should be used to embed.
70          */
71         function get_html( $url, $args = '' ) {
72                 $provider = false;
73
74                 if ( !isset($args['discover']) )
75                         $args['discover'] = true;
76
77                 foreach ( $this->providers as $matchmask => $data ) {
78                         list( $providerurl, $regex ) = $data;
79
80                         // Turn the asterisk-type provider URLs into regex
81                         if ( !$regex ) {
82                                 $matchmask = '#' . str_replace( '___wildcard___', '(.+)', preg_quote( str_replace( '*', '___wildcard___', $matchmask ), '#' ) ) . '#i';
83                                 $matchmask = preg_replace( '|^#http\\\://|', '#https?\://', $matchmask );
84                         }
85
86                         if ( preg_match( $matchmask, $url ) ) {
87                                 $provider = str_replace( '{format}', 'json', $providerurl ); // JSON is easier to deal with than XML
88                                 break;
89                         }
90                 }
91
92                 if ( !$provider && $args['discover'] )
93                         $provider = $this->discover( $url );
94
95                 if ( !$provider || false === $data = $this->fetch( $provider, $url, $args ) )
96                         return false;
97
98                 return apply_filters( 'oembed_result', $this->data2html( $data, $url ), $url, $args );
99         }
100
101         /**
102          * Attempts to find oEmbed provider discovery <link> tags at the given URL.
103          *
104          * @param string $url The URL that should be inspected for discovery <link> tags.
105          * @return bool|string False on failure, otherwise the oEmbed provider URL.
106          */
107         function discover( $url ) {
108                 $providers = array();
109
110                 // Fetch URL content
111                 if ( $html = wp_remote_retrieve_body( wp_remote_get( $url, array( 'reject_unsafe_urls' => true ) ) ) ) {
112
113                         // <link> types that contain oEmbed provider URLs
114                         $linktypes = apply_filters( 'oembed_linktypes', array(
115                                 'application/json+oembed' => 'json',
116                                 'text/xml+oembed' => 'xml',
117                                 'application/xml+oembed' => 'xml', // Incorrect, but used by at least Vimeo
118                         ) );
119
120                         // Strip <body>
121                         $html = substr( $html, 0, stripos( $html, '</head>' ) );
122
123                         // Do a quick check
124                         $tagfound = false;
125                         foreach ( $linktypes as $linktype => $format ) {
126                                 if ( stripos($html, $linktype) ) {
127                                         $tagfound = true;
128                                         break;
129                                 }
130                         }
131
132                         if ( $tagfound && preg_match_all( '/<link([^<>]+)>/i', $html, $links ) ) {
133                                 foreach ( $links[1] as $link ) {
134                                         $atts = shortcode_parse_atts( $link );
135
136                                         if ( !empty($atts['type']) && !empty($linktypes[$atts['type']]) && !empty($atts['href']) ) {
137                                                 $providers[$linktypes[$atts['type']]] = $atts['href'];
138
139                                                 // Stop here if it's JSON (that's all we need)
140                                                 if ( 'json' == $linktypes[$atts['type']] )
141                                                         break;
142                                         }
143                                 }
144                         }
145                 }
146
147                 // JSON is preferred to XML
148                 if ( !empty($providers['json']) )
149                         return $providers['json'];
150                 elseif ( !empty($providers['xml']) )
151                         return $providers['xml'];
152                 else
153                         return false;
154         }
155
156         /**
157          * Connects to a oEmbed provider and returns the result.
158          *
159          * @param string $provider The URL to the oEmbed provider.
160          * @param string $url The URL to the content that is desired to be embedded.
161          * @param array $args Optional arguments. Usually passed from a shortcode.
162          * @return bool|object False on failure, otherwise the result in the form of an object.
163          */
164         function fetch( $provider, $url, $args = '' ) {
165                 $args = wp_parse_args( $args, wp_embed_defaults() );
166
167                 $provider = add_query_arg( 'maxwidth', (int) $args['width'], $provider );
168                 $provider = add_query_arg( 'maxheight', (int) $args['height'], $provider );
169                 $provider = add_query_arg( 'url', urlencode($url), $provider );
170
171                 $provider = apply_filters( 'oembed_fetch_url', $provider, $url, $args );
172
173                 foreach( array( 'json', 'xml' ) as $format ) {
174                         $result = $this->_fetch_with_format( $provider, $format );
175                         if ( is_wp_error( $result ) && 'not-implemented' == $result->get_error_code() )
176                                 continue;
177                         return ( $result && ! is_wp_error( $result ) ) ? $result : false;
178                 }
179                 return false;
180         }
181
182         /**
183          * Fetches result from an oEmbed provider for a specific format and complete provider URL
184          *
185          * @since 3.0.0
186          * @access private
187          * @param string $provider_url_with_args URL to the provider with full arguments list (url, maxheight, etc.)
188          * @param string $format Format to use
189          * @return bool|object False on failure, otherwise the result in the form of an object.
190          */
191         function _fetch_with_format( $provider_url_with_args, $format ) {
192                 $provider_url_with_args = add_query_arg( 'format', $format, $provider_url_with_args );
193                 $response = wp_remote_get( $provider_url_with_args, array( 'reject_unsafe_urls' => true ) );
194                 if ( 501 == wp_remote_retrieve_response_code( $response ) )
195                         return new WP_Error( 'not-implemented' );
196                 if ( ! $body = wp_remote_retrieve_body( $response ) )
197                         return false;
198                 $parse_method = "_parse_$format";
199                 return $this->$parse_method( $body );
200         }
201
202         /**
203          * Parses a json response body.
204          *
205          * @since 3.0.0
206          * @access private
207          */
208         function _parse_json( $response_body ) {
209                 return ( ( $data = json_decode( trim( $response_body ) ) ) && is_object( $data ) ) ? $data : false;
210         }
211
212         /**
213          * Parses an XML response body.
214          *
215          * @since 3.0.0
216          * @access private
217          */
218         function _parse_xml( $response_body ) {
219                 if ( !function_exists('simplexml_load_string') ) {
220                         return false;
221                 }
222                 if ( ! function_exists( 'libxml_disable_entity_loader' ) )
223                         return false;
224
225                 $loader = libxml_disable_entity_loader( true );
226
227                 $errors = libxml_use_internal_errors( true );
228                 $data = simplexml_load_string( $response_body );
229                 libxml_use_internal_errors( $errors );
230
231                 $return = false;
232                 if ( is_object( $data ) ) {
233                         $return = new stdClass;
234                         foreach ( $data as $key => $value ) {
235                                 $return->$key = (string) $value;
236                         }
237                 }
238
239                 libxml_disable_entity_loader( $loader );
240                 return $return;
241         }
242
243         /**
244          * Converts a data object from {@link WP_oEmbed::fetch()} and returns the HTML.
245          *
246          * @param object $data A data object result from an oEmbed provider.
247          * @param string $url The URL to the content that is desired to be embedded.
248          * @return bool|string False on error, otherwise the HTML needed to embed.
249          */
250         function data2html( $data, $url ) {
251                 if ( ! is_object( $data ) || empty( $data->type ) )
252                         return false;
253
254                 $return = false;
255
256                 switch ( $data->type ) {
257                         case 'photo':
258                                 if ( empty( $data->url ) || empty( $data->width ) || empty( $data->height ) )
259                                         break;
260                                 if ( ! is_string( $data->url ) || ! is_numeric( $data->width ) || ! is_numeric( $data->height ) )
261                                         break;
262
263                                 $title = ! empty( $data->title ) && is_string( $data->title ) ? $data->title : '';
264                                 $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>';
265                                 break;
266
267                         case 'video':
268                         case 'rich':
269                                 if ( ! empty( $data->html ) && is_string( $data->html ) )
270                                         $return = $data->html;
271                                 break;
272
273                         case 'link':
274                                 if ( ! empty( $data->title ) && is_string( $data->title ) )
275                                         $return = '<a href="' . esc_url( $url ) . '">' . esc_html( $data->title ) . '</a>';
276                                 break;
277
278                         default:
279                                 $return = false;
280                 }
281
282                 // You can use this filter to add support for custom data types or to filter the result
283                 return apply_filters( 'oembed_dataparse', $return, $data, $url );
284         }
285
286         /**
287          * Strip any new lines from the HTML.
288          *
289          * @access private
290          * @param string $html Existing HTML.
291          * @param object $data Data object from WP_oEmbed::data2html()
292          * @param string $url The original URL passed to oEmbed.
293          * @return string Possibly modified $html
294          */
295         function _strip_newlines( $html, $data, $url ) {
296                 if ( false !== strpos( $html, "\n" ) )
297                         $html = str_replace( array( "\r\n", "\n" ), '', $html );
298
299                 return $html;
300         }
301 }
302
303 /**
304  * Returns the initialized {@link WP_oEmbed} object
305  *
306  * @since 2.9.0
307  * @access private
308  *
309  * @see WP_oEmbed
310  * @uses WP_oEmbed
311  *
312  * @return WP_oEmbed object.
313  */
314 function _wp_oembed_get_object() {
315         static $wp_oembed;
316
317         if ( is_null($wp_oembed) )
318                 $wp_oembed = new WP_oEmbed();
319
320         return $wp_oembed;
321 }