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