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