~canonical-sysadmins/wordpress/4.7.2

« back to all changes in this revision

Viewing changes to wp-includes/class-wp-embed.php

  • Committer: Jacek Nykis
  • Date: 2015-01-05 16:17:05 UTC
  • Revision ID: jacek.nykis@canonical.com-20150105161705-w544l1h5mcg7u4w9
Initial commit

Show diffs side-by-side

added added

removed removed

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