]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/class-wp-embed.php
WordPress 3.9
[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 {
134          *     Shortcode attributes. Optional.
135          *
136          *     @type int $width  Width of the embed in pixels.
137          *     @type int $height Height of the embed in pixels.
138          * }
139          * @param string $url The URL attempting to be embedded.
140          * @return string The embed HTML on success, otherwise the original URL.
141          */
142         function shortcode( $attr, $url = '' ) {
143                 $post = get_post();
144
145                 if ( empty( $url ) )
146                         return '';
147
148                 $rawattr = $attr;
149                 $attr = wp_parse_args( $attr, wp_embed_defaults() );
150
151                 // kses converts & into &amp; and we need to undo this
152                 // See http://core.trac.wordpress.org/ticket/11311
153                 $url = str_replace( '&amp;', '&', $url );
154
155                 // Look for known internal handlers
156                 ksort( $this->handlers );
157                 foreach ( $this->handlers as $priority => $handlers ) {
158                         foreach ( $handlers as $id => $handler ) {
159                                 if ( preg_match( $handler['regex'], $url, $matches ) && is_callable( $handler['callback'] ) ) {
160                                         if ( false !== $return = call_user_func( $handler['callback'], $matches, $attr, $url, $rawattr ) )
161                                                 /**
162                                                  * Filter the returned embed handler.
163                                                  *
164                                                  * @since 2.9.0
165                                                  *
166                                                  * @see WP_Embed::shortcode()
167                                                  *
168                                                  * @param mixed  $return The shortcode callback function to call.
169                                                  * @param string $url    The attempted embed URL.
170                                                  * @param array  $attr   An array of shortcode attributes.
171                                                  */
172                                                 return apply_filters( 'embed_handler_html', $return, $url, $attr );
173                                 }
174                         }
175                 }
176
177                 $post_ID = ( ! empty( $post->ID ) ) ? $post->ID : null;
178                 if ( ! empty( $this->post_ID ) ) // Potentially set by WP_Embed::cache_oembed()
179                         $post_ID = $this->post_ID;
180
181                 // Unknown URL format. Let oEmbed have a go.
182                 if ( $post_ID ) {
183
184                         // Check for a cached result (stored in the post meta)
185                         $cachekey = '_oembed_' . md5( $url . serialize( $attr ) );
186                         if ( $this->usecache ) {
187                                 $cache = get_post_meta( $post_ID, $cachekey, true );
188
189                                 // Failures are cached
190                                 if ( '{{unknown}}' === $cache )
191                                         return $this->maybe_make_link( $url );
192
193                                 if ( ! empty( $cache ) )
194                                         /**
195                                          * Filter the cached oEmbed HTML.
196                                          *
197                                          * @since 2.9.0
198                                          *
199                                          * @see WP_Embed::shortcode()
200                                          *
201                                          * @param mixed  $cache   The cached HTML result, stored in post meta.
202                                          * @param string $url     The attempted embed URL.
203                                          * @param array  $attr    An array of shortcode attributes.
204                                          * @param int    $post_ID Post ID.
205                                          */
206                                         return apply_filters( 'embed_oembed_html', $cache, $url, $attr, $post_ID );
207                         }
208
209                         /**
210                          * Filter whether to inspect the given URL for discoverable <link> tags.
211                          *
212                          * @since 2.9.0
213                          *
214                          * @see WP_oEmbed::discover()
215                          *
216                          * @param bool false Whether to enable <link> tag discovery. Default false.
217                          */
218                         $attr['discover'] = ( apply_filters( 'embed_oembed_discover', false ) && author_can( $post_ID, 'unfiltered_html' ) );
219
220                         // Use oEmbed to get the HTML
221                         $html = wp_oembed_get( $url, $attr );
222
223                         // Cache the result
224                         $cache = ( $html ) ? $html : '{{unknown}}';
225                         update_post_meta( $post_ID, $cachekey, $cache );
226
227                         // If there was a result, return it
228                         if ( $html ) {
229                                 /** This filter is documented in wp-includes/class-wp-embed.php */
230                                 return apply_filters( 'embed_oembed_html', $html, $url, $attr, $post_ID );
231                         }
232                 }
233
234                 // Still unknown
235                 return $this->maybe_make_link( $url );
236         }
237
238         /**
239          * Delete all oEmbed caches.
240          *
241          * @param int $post_ID Post ID to delete the caches for.
242          */
243         function delete_oembed_caches( $post_ID ) {
244                 $post_metas = get_post_custom_keys( $post_ID );
245                 if ( empty($post_metas) )
246                         return;
247
248                 foreach( $post_metas as $post_meta_key ) {
249                         if ( '_oembed_' == substr( $post_meta_key, 0, 8 ) )
250                                 delete_post_meta( $post_ID, $post_meta_key );
251                 }
252         }
253
254         /**
255          * Triggers a caching of all oEmbed results.
256          *
257          * @param int $post_ID Post ID to do the caching for.
258          */
259         function cache_oembed( $post_ID ) {
260                 $post = get_post( $post_ID );
261
262                 $post_types = array( 'post', 'page' );
263                 /**
264                  * Filter the array of post types to cache oEmbed results for.
265                  *
266                  * @since 2.9.0
267                  *
268                  * @param array $post_types Array of post types to cache oEmbed results for. Default 'post', 'page'.
269                  */
270                 if ( empty($post->ID) || !in_array( $post->post_type, apply_filters( 'embed_cache_oembed_types', $post_types ) ) )
271                         return;
272
273                 // Trigger a caching
274                 if ( !empty($post->post_content) ) {
275                         $this->post_ID = $post->ID;
276                         $this->usecache = false;
277
278                         $content = $this->run_shortcode( $post->post_content );
279                         $this->autoembed( $content );
280
281                         $this->usecache = true;
282                 }
283         }
284
285         /**
286          * Passes any unlinked URLs that are on their own line to {@link WP_Embed::shortcode()} for potential embedding.
287          *
288          * @uses WP_Embed::autoembed_callback()
289          *
290          * @param string $content The content to be searched.
291          * @return string Potentially modified $content.
292          */
293         function autoembed( $content ) {
294                 return preg_replace_callback( '|^\s*(https?://[^\s"]+)\s*$|im', array( $this, 'autoembed_callback' ), $content );
295         }
296
297         /**
298          * Callback function for {@link WP_Embed::autoembed()}.
299          *
300          * @uses WP_Embed::shortcode()
301          *
302          * @param array $match A regex match array.
303          * @return string The embed HTML on success, otherwise the original URL.
304          */
305         function autoembed_callback( $match ) {
306                 $oldval = $this->linkifunknown;
307                 $this->linkifunknown = false;
308                 $return = $this->shortcode( array(), $match[1] );
309                 $this->linkifunknown = $oldval;
310
311                 return "\n$return\n";
312         }
313
314         /**
315          * Conditionally makes a hyperlink based on an internal class variable.
316          *
317          * @param string $url URL to potentially be linked.
318          * @return string Linked URL or the original URL.
319          */
320         function maybe_make_link( $url ) {
321                 $output = ( $this->linkifunknown ) ? '<a href="' . esc_url($url) . '">' . esc_html($url) . '</a>' : $url;
322
323                 /**
324                  * Filter the returned, maybe-linked embed URL.
325                  *
326                  * @since 2.9.0
327                  *
328                  * @param string $output The linked or original URL.
329                  * @param string $url    The original URL.
330                  */
331                 return apply_filters( 'embed_maybe_make_link', $output, $url );
332         }
333 }
334 $GLOBALS['wp_embed'] = new WP_Embed();