]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/class-wp-embed.php
WordPress 3.7.2
[autoinstalls/wordpress.git] / wp-includes / class-wp-embed.php
1 <?php
2 /**
3  * API for easily embedding rich media such as videos and images into content.
4  *
5  * @package WordPress
6  * @subpackage Embed
7  * @since 2.9.0
8  */
9 class WP_Embed {
10         var $handlers = array();
11         var $post_ID;
12         var $usecache = true;
13         var $linkifunknown = true;
14
15         /**
16          * Constructor
17          */
18         function __construct() {
19                 // Hack to get the [embed] shortcode to run before wpautop()
20                 add_filter( 'the_content', array( $this, 'run_shortcode' ), 8 );
21
22                 // Shortcode placeholder for strip_shortcodes()
23                 add_shortcode( 'embed', '__return_false' );
24
25                 // Attempts to embed all URLs in a post
26                 add_filter( 'the_content', array( $this, 'autoembed' ), 8 );
27
28                 // When a post is saved, invalidate the oEmbed cache
29                 add_action( 'pre_post_update', array( $this, 'delete_oembed_caches' ) );
30
31                 // After a post is saved, cache oEmbed items via AJAX
32                 add_action( 'edit_form_advanced', array( $this, 'maybe_run_ajax_cache' ) );
33         }
34
35         /**
36          * Process the [embed] shortcode.
37          *
38          * Since the [embed] shortcode needs to be run earlier than other shortcodes,
39          * this function removes all existing shortcodes, registers the [embed] shortcode,
40          * calls {@link do_shortcode()}, and then re-registers the old shortcodes.
41          *
42          * @uses $shortcode_tags
43          * @uses remove_all_shortcodes()
44          * @uses add_shortcode()
45          * @uses do_shortcode()
46          *
47          * @param string $content Content to parse
48          * @return string Content with shortcode parsed
49          */
50         function run_shortcode( $content ) {
51                 global $shortcode_tags;
52
53                 // Back up current registered shortcodes and clear them all out
54                 $orig_shortcode_tags = $shortcode_tags;
55                 remove_all_shortcodes();
56
57                 add_shortcode( 'embed', array( $this, 'shortcode' ) );
58
59                 // Do the shortcode (only the [embed] one is registered)
60                 $content = do_shortcode( $content );
61
62                 // Put the original shortcodes back
63                 $shortcode_tags = $orig_shortcode_tags;
64
65                 return $content;
66         }
67
68         /**
69          * If a post/page was saved, then output JavaScript to make
70          * an AJAX request that will call WP_Embed::cache_oembed().
71          */
72         function maybe_run_ajax_cache() {
73                 $post = get_post();
74
75                 if ( ! $post || empty($_GET['message']) || 1 != $_GET['message'] )
76                         return;
77
78 ?>
79 <script type="text/javascript">
80 /* <![CDATA[ */
81         jQuery(document).ready(function($){
82                 $.get("<?php echo admin_url( 'admin-ajax.php?action=oembed-cache&post=' . $post->ID, 'relative' ); ?>");
83         });
84 /* ]]> */
85 </script>
86 <?php
87         }
88
89         /**
90          * Register an embed handler. Do not use this function directly, use {@link wp_embed_register_handler()} instead.
91          * This function should probably also only be used for sites that do not support oEmbed.
92          *
93          * @param string $id An internal ID/name for the handler. Needs to be unique.
94          * @param string $regex The regex that will be used to see if this handler should be used for a URL.
95          * @param callback $callback The callback function that will be called if the regex is matched.
96          * @param int $priority Optional. Used to specify the order in which the registered handlers will be tested (default: 10). Lower numbers correspond with earlier testing, and handlers with the same priority are tested in the order in which they were added to the action.
97          */
98         function register_handler( $id, $regex, $callback, $priority = 10 ) {
99                 $this->handlers[$priority][$id] = array(
100                         'regex'    => $regex,
101                         'callback' => $callback,
102                 );
103         }
104
105         /**
106          * Unregister a previously registered embed handler. Do not use this function directly, use {@link wp_embed_unregister_handler()} instead.
107          *
108          * @param string $id The handler ID that should be removed.
109          * @param int $priority Optional. The priority of the handler to be removed (default: 10).
110          */
111         function unregister_handler( $id, $priority = 10 ) {
112                 if ( isset($this->handlers[$priority][$id]) )
113                         unset($this->handlers[$priority][$id]);
114         }
115
116         /**
117          * The {@link do_shortcode()} callback function.
118          *
119          * Attempts to convert a URL into embed HTML. Starts by checking the URL against the regex of the registered embed handlers.
120          * If none of the regex matches and it's enabled, then the URL will be given to the {@link WP_oEmbed} class.
121          *
122          * @uses wp_oembed_get()
123          * @uses wp_parse_args()
124          * @uses wp_embed_defaults()
125          * @uses WP_Embed::maybe_make_link()
126          * @uses get_option()
127          * @uses author_can()
128          * @uses wp_cache_get()
129          * @uses wp_cache_set()
130          * @uses get_post_meta()
131          * @uses update_post_meta()
132          *
133          * @param array $attr Shortcode attributes.
134          * @param string $url The URL attempting to be embedded.
135          * @return string The embed HTML on success, otherwise the original URL.
136          */
137         function shortcode( $attr, $url = '' ) {
138                 $post = get_post();
139
140                 if ( empty( $url ) )
141                         return '';
142
143                 $rawattr = $attr;
144                 $attr = wp_parse_args( $attr, wp_embed_defaults() );
145
146                 // kses converts & into &amp; and we need to undo this
147                 // See http://core.trac.wordpress.org/ticket/11311
148                 $url = str_replace( '&amp;', '&', $url );
149
150                 // Look for known internal handlers
151                 ksort( $this->handlers );
152                 foreach ( $this->handlers as $priority => $handlers ) {
153                         foreach ( $handlers as $id => $handler ) {
154                                 if ( preg_match( $handler['regex'], $url, $matches ) && is_callable( $handler['callback'] ) ) {
155                                         if ( false !== $return = call_user_func( $handler['callback'], $matches, $attr, $url, $rawattr ) )
156                                                 /**
157                                                  * Filter the returned embed handler.
158                                                  *
159                                                  * @since 2.9.0
160                                                  *
161                                                  * @param mixed  $return The shortcode callback function to call.
162                                                  * @param string $url    The attempted embed URL.
163                                                  * @param array  $attr   An array of shortcode attributes.
164                                                  */
165                                                 return apply_filters( 'embed_handler_html', $return, $url, $attr );
166                                 }
167                         }
168                 }
169
170                 $post_ID = ( ! empty( $post->ID ) ) ? $post->ID : null;
171                 if ( ! empty( $this->post_ID ) ) // Potentially set by WP_Embed::cache_oembed()
172                         $post_ID = $this->post_ID;
173
174                 // Unknown URL format. Let oEmbed have a go.
175                 if ( $post_ID ) {
176
177                         // Check for a cached result (stored in the post meta)
178                         $cachekey = '_oembed_' . md5( $url . serialize( $attr ) );
179                         if ( $this->usecache ) {
180                                 $cache = get_post_meta( $post_ID, $cachekey, true );
181
182                                 // Failures are cached
183                                 if ( '{{unknown}}' === $cache )
184                                         return $this->maybe_make_link( $url );
185
186                                 if ( ! empty( $cache ) )
187                                         /**
188                                          * Filter the cached oEmbed HTML.
189                                          *
190                                          * @since 2.9.0
191                                          *
192                                          * @param mixed  $cache   The cached HTML result, stored in post meta.
193                                          * @param string $url     The attempted embed URL.
194                                          * @param array  $attr    An array of shortcode attributes.
195                                          * @param int    $post_ID Post ID.
196                                          */
197                                         return apply_filters( 'embed_oembed_html', $cache, $url, $attr, $post_ID );
198                         }
199
200                         /**
201                          * Filter whether to inspect the given URL for discoverable <link> tags.
202                          *
203                          * @see WP_oEmbed::discover()
204                          *
205                          * @param bool false Whether to enable <link> tag discovery. Default false.
206                          */
207                         $attr['discover'] = ( apply_filters( 'embed_oembed_discover', false ) && author_can( $post_ID, 'unfiltered_html' ) );
208
209                         // Use oEmbed to get the HTML
210                         $html = wp_oembed_get( $url, $attr );
211
212                         // Cache the result
213                         $cache = ( $html ) ? $html : '{{unknown}}';
214                         update_post_meta( $post_ID, $cachekey, $cache );
215
216                         // If there was a result, return it
217                         if ( $html ) {
218                                 /** This filter is documented in wp-includes/class-wp-embed.php */
219                                 return apply_filters( 'embed_oembed_html', $html, $url, $attr, $post_ID );
220                         }
221                 }
222
223                 // Still unknown
224                 return $this->maybe_make_link( $url );
225         }
226
227         /**
228          * Delete all oEmbed caches.
229          *
230          * @param int $post_ID Post ID to delete the caches for.
231          */
232         function delete_oembed_caches( $post_ID ) {
233                 $post_metas = get_post_custom_keys( $post_ID );
234                 if ( empty($post_metas) )
235                         return;
236
237                 foreach( $post_metas as $post_meta_key ) {
238                         if ( '_oembed_' == substr( $post_meta_key, 0, 8 ) )
239                                 delete_post_meta( $post_ID, $post_meta_key );
240                 }
241         }
242
243         /**
244          * Triggers a caching of all oEmbed results.
245          *
246          * @param int $post_ID Post ID to do the caching for.
247          */
248         function cache_oembed( $post_ID ) {
249                 $post = get_post( $post_ID );
250
251                 $post_types = array( 'post', 'page' );
252                 /**
253                  * Filter the array of post types to cache oEmbed results for.
254                  *
255                  * @since 2.9.0
256                  *
257                  * @param array $post_types Array of post types to cache oEmbed results for. Default 'post', 'page'.
258                  */
259                 if ( empty($post->ID) || !in_array( $post->post_type, apply_filters( 'embed_cache_oembed_types', $post_types ) ) )
260                         return;
261
262                 // Trigger a caching
263                 if ( !empty($post->post_content) ) {
264                         $this->post_ID = $post->ID;
265                         $this->usecache = false;
266
267                         $content = $this->run_shortcode( $post->post_content );
268                         $this->autoembed( $content );
269
270                         $this->usecache = true;
271                 }
272         }
273
274         /**
275          * Passes any unlinked URLs that are on their own line to {@link WP_Embed::shortcode()} for potential embedding.
276          *
277          * @uses WP_Embed::autoembed_callback()
278          *
279          * @param string $content The content to be searched.
280          * @return string Potentially modified $content.
281          */
282         function autoembed( $content ) {
283                 return preg_replace_callback( '|^\s*(https?://[^\s"]+)\s*$|im', array( $this, 'autoembed_callback' ), $content );
284         }
285
286         /**
287          * Callback function for {@link WP_Embed::autoembed()}.
288          *
289          * @uses WP_Embed::shortcode()
290          *
291          * @param array $match A regex match array.
292          * @return string The embed HTML on success, otherwise the original URL.
293          */
294         function autoembed_callback( $match ) {
295                 $oldval = $this->linkifunknown;
296                 $this->linkifunknown = false;
297                 $return = $this->shortcode( array(), $match[1] );
298                 $this->linkifunknown = $oldval;
299
300                 return "\n$return\n";
301         }
302
303         /**
304          * Conditionally makes a hyperlink based on an internal class variable.
305          *
306          * @param string $url URL to potentially be linked.
307          * @return string Linked URL or the original URL.
308          */
309         function maybe_make_link( $url ) {
310                 $output = ( $this->linkifunknown ) ? '<a href="' . esc_url($url) . '">' . esc_html($url) . '</a>' : $url;
311
312                 /**
313                  * Filter the returned, maybe-linked embed URL.
314                  *
315                  * @since 2.9.0
316                  *
317                  * @param string $output The linked or original URL.
318                  * @param string $url    The original URL.
319                  */
320                 return apply_filters( 'embed_maybe_make_link', $output, $url );
321         }
322 }
323 $GLOBALS['wp_embed'] = new WP_Embed();