]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/class-wp-embed.php
WordPress 4.3.1-scripts
[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         public $handlers = array();
11         public $post_ID;
12         public $usecache = true;
13         public $linkifunknown = true;
14         public $last_attr = array();
15         public $last_url = '';
16
17         /**
18          * When an URL cannot be embedded, return false instead of returning a link
19          * or the URL. Bypasses the 'embed_maybe_make_link' filter.
20          */
21         public $return_false_on_fail = false;
22
23         /**
24          * Constructor
25          */
26         public function __construct() {
27                 // Hack to get the [embed] shortcode to run before wpautop()
28                 add_filter( 'the_content', array( $this, 'run_shortcode' ), 8 );
29
30                 // Shortcode placeholder for strip_shortcodes()
31                 add_shortcode( 'embed', '__return_false' );
32
33                 // Attempts to embed all URLs in a post
34                 add_filter( 'the_content', array( $this, 'autoembed' ), 8 );
35
36                 // After a post is saved, cache oEmbed items via AJAX
37                 add_action( 'edit_form_advanced', array( $this, 'maybe_run_ajax_cache' ) );
38         }
39
40         /**
41          * Process the [embed] shortcode.
42          *
43          * Since the [embed] shortcode needs to be run earlier than other shortcodes,
44          * this function removes all existing shortcodes, registers the [embed] shortcode,
45          * calls {@link do_shortcode()}, and then re-registers the old shortcodes.
46          *
47          * @global array $shortcode_tags
48          *
49          * @param string $content Content to parse
50          * @return string Content with shortcode parsed
51          */
52         public function run_shortcode( $content ) {
53                 global $shortcode_tags;
54
55                 // Back up current registered shortcodes and clear them all out
56                 $orig_shortcode_tags = $shortcode_tags;
57                 remove_all_shortcodes();
58
59                 add_shortcode( 'embed', array( $this, 'shortcode' ) );
60
61                 // Do the shortcode (only the [embed] one is registered)
62                 $content = do_shortcode( $content, true );
63
64                 // Put the original shortcodes back
65                 $shortcode_tags = $orig_shortcode_tags;
66
67                 return $content;
68         }
69
70         /**
71          * If a post/page was saved, then output JavaScript to make
72          * an AJAX request that will call WP_Embed::cache_oembed().
73          */
74         public function maybe_run_ajax_cache() {
75                 $post = get_post();
76
77                 if ( ! $post || empty( $_GET['message'] ) )
78                         return;
79
80 ?>
81 <script type="text/javascript">
82         jQuery(document).ready(function($){
83                 $.get("<?php echo admin_url( 'admin-ajax.php?action=oembed-cache&post=' . $post->ID, 'relative' ); ?>");
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 callable $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         public 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         public function unregister_handler( $id, $priority = 10 ) {
112                 unset( $this->handlers[ $priority ][ $id ] );
113         }
114
115         /**
116          * The {@link do_shortcode()} callback function.
117          *
118          * Attempts to convert a URL into embed HTML. Starts by checking the URL against the regex of the registered embed handlers.
119          * If none of the regex matches and it's enabled, then the URL will be given to the {@link WP_oEmbed} class.
120          *
121          * @param array $attr {
122          *     Shortcode attributes. Optional.
123          *
124          *     @type int $width  Width of the embed in pixels.
125          *     @type int $height Height of the embed in pixels.
126          * }
127          * @param string $url The URL attempting to be embedded.
128          * @return string|false The embed HTML on success, otherwise the original URL.
129          *                      `->maybe_make_link()` can return false on failure.
130          */
131         public function shortcode( $attr, $url = '' ) {
132                 $post = get_post();
133
134                 if ( empty( $url ) && ! empty( $attr['src'] ) ) {
135                         $url = $attr['src'];
136                 }
137
138                 $this->last_url = $url;
139
140                 if ( empty( $url ) ) {
141                         $this->last_attr = $attr;
142                         return '';
143                 }
144
145                 $rawattr = $attr;
146                 $attr = wp_parse_args( $attr, wp_embed_defaults( $url ) );
147
148                 $this->last_attr = $attr;
149
150                 // kses converts & into &amp; and we need to undo this
151                 // See https://core.trac.wordpress.org/ticket/11311
152                 $url = str_replace( '&amp;', '&', $url );
153
154                 // Look for known internal handlers
155                 ksort( $this->handlers );
156                 foreach ( $this->handlers as $priority => $handlers ) {
157                         foreach ( $handlers as $id => $handler ) {
158                                 if ( preg_match( $handler['regex'], $url, $matches ) && is_callable( $handler['callback'] ) ) {
159                                         if ( false !== $return = call_user_func( $handler['callback'], $matches, $attr, $url, $rawattr ) )
160                                                 /**
161                                                  * Filter the returned embed handler.
162                                                  *
163                                                  * @since 2.9.0
164                                                  *
165                                                  * @see WP_Embed::shortcode()
166                                                  *
167                                                  * @param mixed  $return The shortcode callback function to call.
168                                                  * @param string $url    The attempted embed URL.
169                                                  * @param array  $attr   An array of shortcode attributes.
170                                                  */
171                                                 return apply_filters( 'embed_handler_html', $return, $url, $attr );
172                                 }
173                         }
174                 }
175
176                 $post_ID = ( ! empty( $post->ID ) ) ? $post->ID : null;
177                 if ( ! empty( $this->post_ID ) ) // Potentially set by WP_Embed::cache_oembed()
178                         $post_ID = $this->post_ID;
179
180                 // Unknown URL format. Let oEmbed have a go.
181                 if ( $post_ID ) {
182
183                         // Check for a cached result (stored in the post meta)
184                         $key_suffix = md5( $url . serialize( $attr ) );
185                         $cachekey = '_oembed_' . $key_suffix;
186                         $cachekey_time = '_oembed_time_' . $key_suffix;
187
188                         /**
189                          * Filter the oEmbed TTL value (time to live).
190                          *
191                          * @since 4.0.0
192                          *
193                          * @param int    $time    Time to live (in seconds).
194                          * @param string $url     The attempted embed URL.
195                          * @param array  $attr    An array of shortcode attributes.
196                          * @param int    $post_ID Post ID.
197                          */
198                         $ttl = apply_filters( 'oembed_ttl', DAY_IN_SECONDS, $url, $attr, $post_ID );
199
200                         $cache = get_post_meta( $post_ID, $cachekey, true );
201                         $cache_time = get_post_meta( $post_ID, $cachekey_time, true );
202
203                         if ( ! $cache_time ) {
204                                 $cache_time = 0;
205                         }
206
207                         $cached_recently = ( time() - $cache_time ) < $ttl;
208
209                         if ( $this->usecache || $cached_recently ) {
210                                 // Failures are cached. Serve one if we're using the cache.
211                                 if ( '{{unknown}}' === $cache )
212                                         return $this->maybe_make_link( $url );
213
214                                 if ( ! empty( $cache ) ) {
215                                         /**
216                                          * Filter the cached oEmbed HTML.
217                                          *
218                                          * @since 2.9.0
219                                          *
220                                          * @see WP_Embed::shortcode()
221                                          *
222                                          * @param mixed  $cache   The cached HTML result, stored in post meta.
223                                          * @param string $url     The attempted embed URL.
224                                          * @param array  $attr    An array of shortcode attributes.
225                                          * @param int    $post_ID Post ID.
226                                          */
227                                         return apply_filters( 'embed_oembed_html', $cache, $url, $attr, $post_ID );
228                                 }
229                         }
230
231                         /**
232                          * Filter whether to inspect the given URL for discoverable link tags.
233                          *
234                          * @since 2.9.0
235                          *
236                          * @see WP_oEmbed::discover()
237                          *
238                          * @param bool $enable Whether to enable `<link>` tag discovery. Default false.
239                          */
240                         $attr['discover'] = ( apply_filters( 'embed_oembed_discover', false ) && author_can( $post_ID, 'unfiltered_html' ) );
241
242                         // Use oEmbed to get the HTML
243                         $html = wp_oembed_get( $url, $attr );
244
245                         // Maybe cache the result
246                         if ( $html ) {
247                                 update_post_meta( $post_ID, $cachekey, $html );
248                                 update_post_meta( $post_ID, $cachekey_time, time() );
249                         } elseif ( ! $cache ) {
250                                 update_post_meta( $post_ID, $cachekey, '{{unknown}}' );
251                         }
252
253                         // If there was a result, return it
254                         if ( $html ) {
255                                 /** This filter is documented in wp-includes/class-wp-embed.php */
256                                 return apply_filters( 'embed_oembed_html', $html, $url, $attr, $post_ID );
257                         }
258                 }
259
260                 // Still unknown
261                 return $this->maybe_make_link( $url );
262         }
263
264         /**
265          * Delete all oEmbed caches. Unused by core as of 4.0.0.
266          *
267          * @param int $post_ID Post ID to delete the caches for.
268          */
269         public function delete_oembed_caches( $post_ID ) {
270                 $post_metas = get_post_custom_keys( $post_ID );
271                 if ( empty($post_metas) )
272                         return;
273
274                 foreach( $post_metas as $post_meta_key ) {
275                         if ( '_oembed_' == substr( $post_meta_key, 0, 8 ) )
276                                 delete_post_meta( $post_ID, $post_meta_key );
277                 }
278         }
279
280         /**
281          * Triggers a caching of all oEmbed results.
282          *
283          * @param int $post_ID Post ID to do the caching for.
284          */
285         public function cache_oembed( $post_ID ) {
286                 $post = get_post( $post_ID );
287
288                 $post_types = get_post_types( array( 'show_ui' => true ) );
289                 /**
290                  * Filter the array of post types to cache oEmbed results for.
291                  *
292                  * @since 2.9.0
293                  *
294                  * @param array $post_types Array of post types to cache oEmbed results for. Defaults to post types with `show_ui` set to true.
295                  */
296                 if ( empty( $post->ID ) || ! in_array( $post->post_type, apply_filters( 'embed_cache_oembed_types', $post_types ) ) ){
297                         return;
298                 }
299
300                 // Trigger a caching
301                 if ( ! empty( $post->post_content ) ) {
302                         $this->post_ID = $post->ID;
303                         $this->usecache = false;
304
305                         $content = $this->run_shortcode( $post->post_content );
306                         $this->autoembed( $content );
307
308                         $this->usecache = true;
309                 }
310         }
311
312         /**
313          * Passes any unlinked URLs that are on their own line to {@link WP_Embed::shortcode()} for potential embedding.
314          *
315          * @uses WP_Embed::autoembed_callback()
316          *
317          * @param string $content The content to be searched.
318          * @return string Potentially modified $content.
319          */
320         public function autoembed( $content ) {
321                 // Replace line breaks from all HTML elements with placeholders.
322                 $content = wp_replace_in_html_tags( $content, array( "\n" => '<!-- wp-line-break -->' ) );
323
324                 // Find URLs that are on their own line.
325                 $content = preg_replace_callback( '|^(\s*)(https?://[^\s"]+)(\s*)$|im', array( $this, 'autoembed_callback' ), $content );
326
327                 // Put the line breaks back.
328                 return str_replace( '<!-- wp-line-break -->', "\n", $content );
329         }
330
331         /**
332          * Callback function for {@link WP_Embed::autoembed()}.
333          *
334          * @param array $match A regex match array.
335          * @return string The embed HTML on success, otherwise the original URL.
336          */
337         public function autoembed_callback( $match ) {
338                 $oldval = $this->linkifunknown;
339                 $this->linkifunknown = false;
340                 $return = $this->shortcode( array(), $match[2] );
341                 $this->linkifunknown = $oldval;
342
343                 return $match[1] . $return . $match[3];
344         }
345
346         /**
347          * Conditionally makes a hyperlink based on an internal class variable.
348          *
349          * @param string $url URL to potentially be linked.
350          * @return false|string Linked URL or the original URL. False if 'return_false_on_fail' is true.
351          */
352         public function maybe_make_link( $url ) {
353                 if ( $this->return_false_on_fail ) {
354                         return false;
355                 }
356
357                 $output = ( $this->linkifunknown ) ? '<a href="' . esc_url($url) . '">' . esc_html($url) . '</a>' : $url;
358
359                 /**
360                  * Filter the returned, maybe-linked embed URL.
361                  *
362                  * @since 2.9.0
363                  *
364                  * @param string $output The linked or original URL.
365                  * @param string $url    The original URL.
366                  */
367                 return apply_filters( 'embed_maybe_make_link', $output, $url );
368         }
369 }
370 $GLOBALS['wp_embed'] = new WP_Embed();