]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/class-wp-embed.php
WordPress 4.4.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                 add_action( 'edit_page_form', array( $this, 'maybe_run_ajax_cache' ) );
39         }
40
41         /**
42          * Process the [embed] shortcode.
43          *
44          * Since the [embed] shortcode needs to be run earlier than other shortcodes,
45          * this function removes all existing shortcodes, registers the [embed] shortcode,
46          * calls {@link do_shortcode()}, and then re-registers the old shortcodes.
47          *
48          * @global array $shortcode_tags
49          *
50          * @param string $content Content to parse
51          * @return string Content with shortcode parsed
52          */
53         public function run_shortcode( $content ) {
54                 global $shortcode_tags;
55
56                 // Back up current registered shortcodes and clear them all out
57                 $orig_shortcode_tags = $shortcode_tags;
58                 remove_all_shortcodes();
59
60                 add_shortcode( 'embed', array( $this, 'shortcode' ) );
61
62                 // Do the shortcode (only the [embed] one is registered)
63                 $content = do_shortcode( $content, true );
64
65                 // Put the original shortcodes back
66                 $shortcode_tags = $orig_shortcode_tags;
67
68                 return $content;
69         }
70
71         /**
72          * If a post/page was saved, then output JavaScript to make
73          * an AJAX request that will call WP_Embed::cache_oembed().
74          */
75         public function maybe_run_ajax_cache() {
76                 $post = get_post();
77
78                 if ( ! $post || empty( $_GET['message'] ) )
79                         return;
80
81 ?>
82 <script type="text/javascript">
83         jQuery(document).ready(function($){
84                 $.get("<?php echo admin_url( 'admin-ajax.php?action=oembed-cache&post=' . $post->ID, 'relative' ); ?>");
85         });
86 </script>
87 <?php
88         }
89
90         /**
91          * Register an embed handler. Do not use this function directly, use {@link wp_embed_register_handler()} instead.
92          * This function should probably also only be used for sites that do not support oEmbed.
93          *
94          * @param string $id An internal ID/name for the handler. Needs to be unique.
95          * @param string $regex The regex that will be used to see if this handler should be used for a URL.
96          * @param callable $callback The callback function that will be called if the regex is matched.
97          * @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.
98          */
99         public function register_handler( $id, $regex, $callback, $priority = 10 ) {
100                 $this->handlers[$priority][$id] = array(
101                         'regex'    => $regex,
102                         'callback' => $callback,
103                 );
104         }
105
106         /**
107          * Unregister a previously registered embed handler. Do not use this function directly, use {@link wp_embed_unregister_handler()} instead.
108          *
109          * @param string $id The handler ID that should be removed.
110          * @param int $priority Optional. The priority of the handler to be removed (default: 10).
111          */
112         public function unregister_handler( $id, $priority = 10 ) {
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          * @param array $attr {
123          *     Shortcode attributes. Optional.
124          *
125          *     @type int $width  Width of the embed in pixels.
126          *     @type int $height Height of the embed in pixels.
127          * }
128          * @param string $url The URL attempting to be embedded.
129          * @return string|false The embed HTML on success, otherwise the original URL.
130          *                      `->maybe_make_link()` can return false on failure.
131          */
132         public function shortcode( $attr, $url = '' ) {
133                 $post = get_post();
134
135                 if ( empty( $url ) && ! empty( $attr['src'] ) ) {
136                         $url = $attr['src'];
137                 }
138
139                 $this->last_url = $url;
140
141                 if ( empty( $url ) ) {
142                         $this->last_attr = $attr;
143                         return '';
144                 }
145
146                 $rawattr = $attr;
147                 $attr = wp_parse_args( $attr, wp_embed_defaults( $url ) );
148
149                 $this->last_attr = $attr;
150
151                 // kses converts & into &amp; and we need to undo this
152                 // See https://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                         $key_suffix = md5( $url . serialize( $attr ) );
186                         $cachekey = '_oembed_' . $key_suffix;
187                         $cachekey_time = '_oembed_time_' . $key_suffix;
188
189                         /**
190                          * Filter the oEmbed TTL value (time to live).
191                          *
192                          * @since 4.0.0
193                          *
194                          * @param int    $time    Time to live (in seconds).
195                          * @param string $url     The attempted embed URL.
196                          * @param array  $attr    An array of shortcode attributes.
197                          * @param int    $post_ID Post ID.
198                          */
199                         $ttl = apply_filters( 'oembed_ttl', DAY_IN_SECONDS, $url, $attr, $post_ID );
200
201                         $cache = get_post_meta( $post_ID, $cachekey, true );
202                         $cache_time = get_post_meta( $post_ID, $cachekey_time, true );
203
204                         if ( ! $cache_time ) {
205                                 $cache_time = 0;
206                         }
207
208                         $cached_recently = ( time() - $cache_time ) < $ttl;
209
210                         if ( $this->usecache || $cached_recently ) {
211                                 // Failures are cached. Serve one if we're using the cache.
212                                 if ( '{{unknown}}' === $cache )
213                                         return $this->maybe_make_link( $url );
214
215                                 if ( ! empty( $cache ) ) {
216                                         /**
217                                          * Filter the cached oEmbed HTML.
218                                          *
219                                          * @since 2.9.0
220                                          *
221                                          * @see WP_Embed::shortcode()
222                                          *
223                                          * @param mixed  $cache   The cached HTML result, stored in post meta.
224                                          * @param string $url     The attempted embed URL.
225                                          * @param array  $attr    An array of shortcode attributes.
226                                          * @param int    $post_ID Post ID.
227                                          */
228                                         return apply_filters( 'embed_oembed_html', $cache, $url, $attr, $post_ID );
229                                 }
230                         }
231
232                         /**
233                          * Filter whether to inspect the given URL for discoverable link tags.
234                          *
235                          * @since 2.9.0
236                          * @since 4.4.0 The default value changed to true.
237                          *
238                          * @see WP_oEmbed::discover()
239                          *
240                          * @param bool $enable Whether to enable `<link>` tag discovery. Default true.
241                          */
242                         $attr['discover'] = ( apply_filters( 'embed_oembed_discover', true ) );
243
244                         // Use oEmbed to get the HTML
245                         $html = wp_oembed_get( $url, $attr );
246
247                         // Maybe cache the result
248                         if ( $html ) {
249                                 update_post_meta( $post_ID, $cachekey, $html );
250                                 update_post_meta( $post_ID, $cachekey_time, time() );
251                         } elseif ( ! $cache ) {
252                                 update_post_meta( $post_ID, $cachekey, '{{unknown}}' );
253                         }
254
255                         // If there was a result, return it
256                         if ( $html ) {
257                                 /** This filter is documented in wp-includes/class-wp-embed.php */
258                                 return apply_filters( 'embed_oembed_html', $html, $url, $attr, $post_ID );
259                         }
260                 }
261
262                 // Still unknown
263                 return $this->maybe_make_link( $url );
264         }
265
266         /**
267          * Delete all oEmbed caches. Unused by core as of 4.0.0.
268          *
269          * @param int $post_ID Post ID to delete the caches for.
270          */
271         public function delete_oembed_caches( $post_ID ) {
272                 $post_metas = get_post_custom_keys( $post_ID );
273                 if ( empty($post_metas) )
274                         return;
275
276                 foreach ( $post_metas as $post_meta_key ) {
277                         if ( '_oembed_' == substr( $post_meta_key, 0, 8 ) )
278                                 delete_post_meta( $post_ID, $post_meta_key );
279                 }
280         }
281
282         /**
283          * Triggers a caching of all oEmbed results.
284          *
285          * @param int $post_ID Post ID to do the caching for.
286          */
287         public function cache_oembed( $post_ID ) {
288                 $post = get_post( $post_ID );
289
290                 $post_types = get_post_types( array( 'show_ui' => true ) );
291                 /**
292                  * Filter the array of post types to cache oEmbed results for.
293                  *
294                  * @since 2.9.0
295                  *
296                  * @param array $post_types Array of post types to cache oEmbed results for. Defaults to post types with `show_ui` set to true.
297                  */
298                 if ( empty( $post->ID ) || ! in_array( $post->post_type, apply_filters( 'embed_cache_oembed_types', $post_types ) ) ){
299                         return;
300                 }
301
302                 // Trigger a caching
303                 if ( ! empty( $post->post_content ) ) {
304                         $this->post_ID = $post->ID;
305                         $this->usecache = false;
306
307                         $content = $this->run_shortcode( $post->post_content );
308                         $this->autoembed( $content );
309
310                         $this->usecache = true;
311                 }
312         }
313
314         /**
315          * Passes any unlinked URLs that are on their own line to {@link WP_Embed::shortcode()} for potential embedding.
316          *
317          * @uses WP_Embed::autoembed_callback()
318          *
319          * @param string $content The content to be searched.
320          * @return string Potentially modified $content.
321          */
322         public function autoembed( $content ) {
323                 // Replace line breaks from all HTML elements with placeholders.
324                 $content = wp_replace_in_html_tags( $content, array( "\n" => '<!-- wp-line-break -->' ) );
325
326                 // Find URLs that are on their own line.
327                 $content = preg_replace_callback( '|^(\s*)(https?://[^\s"]+)(\s*)$|im', array( $this, 'autoembed_callback' ), $content );
328
329                 // Put the line breaks back.
330                 return str_replace( '<!-- wp-line-break -->', "\n", $content );
331         }
332
333         /**
334          * Callback function for {@link WP_Embed::autoembed()}.
335          *
336          * @param array $match A regex match array.
337          * @return string The embed HTML on success, otherwise the original URL.
338          */
339         public function autoembed_callback( $match ) {
340                 $oldval = $this->linkifunknown;
341                 $this->linkifunknown = false;
342                 $return = $this->shortcode( array(), $match[2] );
343                 $this->linkifunknown = $oldval;
344
345                 return $match[1] . $return . $match[3];
346         }
347
348         /**
349          * Conditionally makes a hyperlink based on an internal class variable.
350          *
351          * @param string $url URL to potentially be linked.
352          * @return false|string Linked URL or the original URL. False if 'return_false_on_fail' is true.
353          */
354         public function maybe_make_link( $url ) {
355                 if ( $this->return_false_on_fail ) {
356                         return false;
357                 }
358
359                 $output = ( $this->linkifunknown ) ? '<a href="' . esc_url($url) . '">' . esc_html($url) . '</a>' : $url;
360
361                 /**
362                  * Filter the returned, maybe-linked embed URL.
363                  *
364                  * @since 2.9.0
365                  *
366                  * @param string $output The linked or original URL.
367                  * @param string $url    The original URL.
368                  */
369                 return apply_filters( 'embed_maybe_make_link', $output, $url );
370         }
371 }
372 $GLOBALS['wp_embed'] = new WP_Embed();