]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/shortcodes.php
WordPress 4.3.1
[autoinstalls/wordpress.git] / wp-includes / shortcodes.php
1 <?php
2 /**
3  * WordPress API for creating bbcode like tags or what WordPress calls
4  * "shortcodes." The tag and attribute parsing or regular expression code is
5  * based on the Textpattern tag parser.
6  *
7  * A few examples are below:
8  *
9  * [shortcode /]
10  * [shortcode foo="bar" baz="bing" /]
11  * [shortcode foo="bar"]content[/shortcode]
12  *
13  * Shortcode tags support attributes and enclosed content, but does not entirely
14  * support inline shortcodes in other shortcodes. You will have to call the
15  * shortcode parser in your function to account for that.
16  *
17  * {@internal
18  * Please be aware that the above note was made during the beta of WordPress 2.6
19  * and in the future may not be accurate. Please update the note when it is no
20  * longer the case.}}
21  *
22  * To apply shortcode tags to content:
23  *
24  *     $out = do_shortcode( $content );
25  *
26  * @link https://codex.wordpress.org/Shortcode_API
27  *
28  * @package WordPress
29  * @subpackage Shortcodes
30  * @since 2.5.0
31  */
32
33 /**
34  * Container for storing shortcode tags and their hook to call for the shortcode
35  *
36  * @since 2.5.0
37  *
38  * @name $shortcode_tags
39  * @var array
40  * @global array $shortcode_tags
41  */
42 $shortcode_tags = array();
43
44 /**
45  * Add hook for shortcode tag.
46  *
47  * There can only be one hook for each shortcode. Which means that if another
48  * plugin has a similar shortcode, it will override yours or yours will override
49  * theirs depending on which order the plugins are included and/or ran.
50  *
51  * Simplest example of a shortcode tag using the API:
52  *
53  *     // [footag foo="bar"]
54  *     function footag_func( $atts ) {
55  *         return "foo = {
56  *             $atts[foo]
57  *         }";
58  *     }
59  *     add_shortcode( 'footag', 'footag_func' );
60  *
61  * Example with nice attribute defaults:
62  *
63  *     // [bartag foo="bar"]
64  *     function bartag_func( $atts ) {
65  *         $args = shortcode_atts( array(
66  *             'foo' => 'no foo',
67  *             'baz' => 'default baz',
68  *         ), $atts );
69  *
70  *         return "foo = {$args['foo']}";
71  *     }
72  *     add_shortcode( 'bartag', 'bartag_func' );
73  *
74  * Example with enclosed content:
75  *
76  *     // [baztag]content[/baztag]
77  *     function baztag_func( $atts, $content = '' ) {
78  *         return "content = $content";
79  *     }
80  *     add_shortcode( 'baztag', 'baztag_func' );
81  *
82  * @since 2.5.0
83  *
84  * @global array $shortcode_tags
85  *
86  * @param string   $tag  Shortcode tag to be searched in post content.
87  * @param callable $func Hook to run when shortcode is found.
88  */
89 function add_shortcode($tag, $func) {
90         global $shortcode_tags;
91         $shortcode_tags[ $tag ] = $func;
92 }
93
94 /**
95  * Removes hook for shortcode.
96  *
97  * @since 2.5.0
98  *
99  * @global array $shortcode_tags
100  *
101  * @param string $tag Shortcode tag to remove hook for.
102  */
103 function remove_shortcode($tag) {
104         global $shortcode_tags;
105
106         unset($shortcode_tags[$tag]);
107 }
108
109 /**
110  * Clear all shortcodes.
111  *
112  * This function is simple, it clears all of the shortcode tags by replacing the
113  * shortcodes global by a empty array. This is actually a very efficient method
114  * for removing all shortcodes.
115  *
116  * @since 2.5.0
117  *
118  * @global array $shortcode_tags
119  */
120 function remove_all_shortcodes() {
121         global $shortcode_tags;
122
123         $shortcode_tags = array();
124 }
125
126 /**
127  * Whether a registered shortcode exists named $tag
128  *
129  * @since 3.6.0
130  *
131  * @global array $shortcode_tags List of shortcode tags and their callback hooks.
132  *
133  * @param string $tag Shortcode tag to check.
134  * @return bool Whether the given shortcode exists.
135  */
136 function shortcode_exists( $tag ) {
137         global $shortcode_tags;
138         return array_key_exists( $tag, $shortcode_tags );
139 }
140
141 /**
142  * Whether the passed content contains the specified shortcode
143  *
144  * @since 3.6.0
145  *
146  * @global array $shortcode_tags
147  *
148  * @param string $content Content to search for shortcodes.
149  * @param string $tag     Shortcode tag to check.
150  * @return bool Whether the passed content contains the given shortcode.
151  */
152 function has_shortcode( $content, $tag ) {
153         if ( false === strpos( $content, '[' ) ) {
154                 return false;
155         }
156
157         if ( shortcode_exists( $tag ) ) {
158                 preg_match_all( '/' . get_shortcode_regex() . '/s', $content, $matches, PREG_SET_ORDER );
159                 if ( empty( $matches ) )
160                         return false;
161
162                 foreach ( $matches as $shortcode ) {
163                         if ( $tag === $shortcode[2] ) {
164                                 return true;
165                         } elseif ( ! empty( $shortcode[5] ) && has_shortcode( $shortcode[5], $tag ) ) {
166                                 return true;
167                         }
168                 }
169         }
170         return false;
171 }
172
173 /**
174  * Search content for shortcodes and filter shortcodes through their hooks.
175  *
176  * If there are no shortcode tags defined, then the content will be returned
177  * without any filtering. This might cause issues when plugins are disabled but
178  * the shortcode will still show up in the post or content.
179  *
180  * @since 2.5.0
181  *
182  * @global array $shortcode_tags List of shortcode tags and their callback hooks.
183  *
184  * @param string $content Content to search for shortcodes.
185  * @param bool $ignore_html When true, shortcodes inside HTML elements will be skipped.
186  * @return string Content with shortcodes filtered out.
187  */
188 function do_shortcode( $content, $ignore_html = false ) {
189         global $shortcode_tags;
190
191         if ( false === strpos( $content, '[' ) ) {
192                 return $content;
193         }
194
195         if (empty($shortcode_tags) || !is_array($shortcode_tags))
196                 return $content;
197
198         $tagnames = array_keys($shortcode_tags);
199         $tagregexp = join( '|', array_map('preg_quote', $tagnames) );
200         $pattern = "/\\[($tagregexp)/s";
201
202         if ( 1 !== preg_match( $pattern, $content ) ) {
203                 // Avoids parsing HTML when there are no shortcodes or embeds anyway.
204                 return $content;
205         }
206
207         $content = do_shortcodes_in_html_tags( $content, $ignore_html );
208
209         $pattern = get_shortcode_regex();
210         $content = preg_replace_callback( "/$pattern/s", 'do_shortcode_tag', $content );
211
212         // Always restore square braces so we don't break things like <!--[if IE ]>
213         $content = unescape_invalid_shortcodes( $content );
214
215         return $content;
216 }
217
218 /**
219  * Retrieve the shortcode regular expression for searching.
220  *
221  * The regular expression combines the shortcode tags in the regular expression
222  * in a regex class.
223  *
224  * The regular expression contains 6 different sub matches to help with parsing.
225  *
226  * 1 - An extra [ to allow for escaping shortcodes with double [[]]
227  * 2 - The shortcode name
228  * 3 - The shortcode argument list
229  * 4 - The self closing /
230  * 5 - The content of a shortcode when it wraps some content.
231  * 6 - An extra ] to allow for escaping shortcodes with double [[]]
232  *
233  * @since 2.5.0
234  *
235  * @global array $shortcode_tags
236  *
237  * @return string The shortcode search regular expression
238  */
239 function get_shortcode_regex() {
240         global $shortcode_tags;
241         $tagnames = array_keys($shortcode_tags);
242         $tagregexp = join( '|', array_map('preg_quote', $tagnames) );
243
244         // WARNING! Do not change this regex without changing do_shortcode_tag() and strip_shortcode_tag()
245         // Also, see shortcode_unautop() and shortcode.js.
246         return
247                   '\\['                              // Opening bracket
248                 . '(\\[?)'                           // 1: Optional second opening bracket for escaping shortcodes: [[tag]]
249                 . "($tagregexp)"                     // 2: Shortcode name
250                 . '(?![\\w-])'                       // Not followed by word character or hyphen
251                 . '('                                // 3: Unroll the loop: Inside the opening shortcode tag
252                 .     '[^\\]\\/]*'                   // Not a closing bracket or forward slash
253                 .     '(?:'
254                 .         '\\/(?!\\])'               // A forward slash not followed by a closing bracket
255                 .         '[^\\]\\/]*'               // Not a closing bracket or forward slash
256                 .     ')*?'
257                 . ')'
258                 . '(?:'
259                 .     '(\\/)'                        // 4: Self closing tag ...
260                 .     '\\]'                          // ... and closing bracket
261                 . '|'
262                 .     '\\]'                          // Closing bracket
263                 .     '(?:'
264                 .         '('                        // 5: Unroll the loop: Optionally, anything between the opening and closing shortcode tags
265                 .             '[^\\[]*+'             // Not an opening bracket
266                 .             '(?:'
267                 .                 '\\[(?!\\/\\2\\])' // An opening bracket not followed by the closing shortcode tag
268                 .                 '[^\\[]*+'         // Not an opening bracket
269                 .             ')*+'
270                 .         ')'
271                 .         '\\[\\/\\2\\]'             // Closing shortcode tag
272                 .     ')?'
273                 . ')'
274                 . '(\\]?)';                          // 6: Optional second closing brocket for escaping shortcodes: [[tag]]
275 }
276
277 /**
278  * Regular Expression callable for do_shortcode() for calling shortcode hook.
279  * @see get_shortcode_regex for details of the match array contents.
280  *
281  * @since 2.5.0
282  * @access private
283  *
284  * @global array $shortcode_tags
285  *
286  * @param array $m Regular expression match array
287  * @return string|false False on failure.
288  */
289 function do_shortcode_tag( $m ) {
290         global $shortcode_tags;
291
292         // allow [[foo]] syntax for escaping a tag
293         if ( $m[1] == '[' && $m[6] == ']' ) {
294                 return substr($m[0], 1, -1);
295         }
296
297         $tag = $m[2];
298         $attr = shortcode_parse_atts( $m[3] );
299
300         if ( ! is_callable( $shortcode_tags[ $tag ] ) ) {
301                 $message = sprintf( __( 'Attempting to parse a shortcode without a valid callback: %s' ), $tag );
302                 _doing_it_wrong( __FUNCTION__, $message, '4.3.0' );
303                 return $m[0];
304         }
305
306         if ( isset( $m[5] ) ) {
307                 // enclosing tag - extra parameter
308                 return $m[1] . call_user_func( $shortcode_tags[$tag], $attr, $m[5], $tag ) . $m[6];
309         } else {
310                 // self-closing tag
311                 return $m[1] . call_user_func( $shortcode_tags[$tag], $attr, null,  $tag ) . $m[6];
312         }
313 }
314
315 /**
316  * Search only inside HTML elements for shortcodes and process them.
317  *
318  * Any [ or ] characters remaining inside elements will be HTML encoded
319  * to prevent interference with shortcodes that are outside the elements.
320  * Assumes $content processed by KSES already.  Users with unfiltered_html
321  * capability may get unexpected output if angle braces are nested in tags.
322  *
323  * @since 4.2.3
324  *
325  * @param string $content Content to search for shortcodes
326  * @param bool $ignore_html When true, all square braces inside elements will be encoded.
327  * @return string Content with shortcodes filtered out.
328  */
329 function do_shortcodes_in_html_tags( $content, $ignore_html ) {
330         // Normalize entities in unfiltered HTML before adding placeholders.
331         $trans = array( '&#91;' => '&#091;', '&#93;' => '&#093;' );
332         $content = strtr( $content, $trans );
333         $trans = array( '[' => '&#91;', ']' => '&#93;' );
334
335         $pattern = get_shortcode_regex();
336         $textarr = wp_html_split( $content );
337
338         foreach ( $textarr as &$element ) {
339                 if ( '' == $element || '<' !== $element[0] ) {
340                         continue;
341                 }
342
343                 $noopen = false === strpos( $element, '[' );
344                 $noclose = false === strpos( $element, ']' );
345                 if ( $noopen || $noclose ) {
346                         // This element does not contain shortcodes.
347                         if ( $noopen xor $noclose ) {
348                                 // Need to encode stray [ or ] chars.
349                                 $element = strtr( $element, $trans );
350                         }
351                         continue;
352                 }
353
354                 if ( $ignore_html || '<!--' === substr( $element, 0, 4 ) || '<![CDATA[' === substr( $element, 0, 9 ) ) {
355                         // Encode all [ and ] chars.
356                         $element = strtr( $element, $trans );
357                         continue;
358                 }
359
360                 $attributes = wp_kses_attr_parse( $element );
361                 if ( false === $attributes ) {
362                         // Some plugins are doing things like [name] <[email]>.
363                         if ( 1 === preg_match( '%^<\s*\[\[?[^\[\]]+\]%', $element ) ) {
364                                 $element = preg_replace_callback( "/$pattern/s", 'do_shortcode_tag', $element );
365                         }
366
367                         // Looks like we found some crazy unfiltered HTML.  Skipping it for sanity.
368                         $element = strtr( $element, $trans );
369                         continue;
370                 }
371
372                 // Get element name
373                 $front = array_shift( $attributes );
374                 $back = array_pop( $attributes );
375                 $matches = array();
376                 preg_match('%[a-zA-Z0-9]+%', $front, $matches);
377                 $elname = $matches[0];
378
379                 // Look for shortcodes in each attribute separately.
380                 foreach ( $attributes as &$attr ) {
381                         $open = strpos( $attr, '[' );
382                         $close = strpos( $attr, ']' );
383                         if ( false === $open || false === $close ) {
384                                 continue; // Go to next attribute.  Square braces will be escaped at end of loop.
385                         }
386                         $double = strpos( $attr, '"' );
387                         $single = strpos( $attr, "'" );
388                         if ( ( false === $single || $open < $single ) && ( false === $double || $open < $double ) ) {
389                                 // $attr like '[shortcode]' or 'name = [shortcode]' implies unfiltered_html.
390                                 // In this specific situation we assume KSES did not run because the input
391                                 // was written by an administrator, so we should avoid changing the output
392                                 // and we do not need to run KSES here.
393                                 $attr = preg_replace_callback( "/$pattern/s", 'do_shortcode_tag', $attr );
394                         } else {
395                                 // $attr like 'name = "[shortcode]"' or "name = '[shortcode]'"
396                                 // We do not know if $content was unfiltered. Assume KSES ran before shortcodes.
397                                 $count = 0;
398                                 $new_attr = preg_replace_callback( "/$pattern/s", 'do_shortcode_tag', $attr, -1, $count );
399                                 if ( $count > 0 ) {
400                                         // Sanitize the shortcode output using KSES.
401                                         $new_attr = wp_kses_one_attr( $new_attr, $elname );
402                                         if ( '' !== trim( $new_attr ) ) {
403                                                 // The shortcode is safe to use now.
404                                                 $attr = $new_attr;
405                                         }
406                                 }
407                         }
408                 }
409                 $element = $front . implode( '', $attributes ) . $back;
410
411                 // Now encode any remaining [ or ] chars.
412                 $element = strtr( $element, $trans );
413         }
414
415         $content = implode( '', $textarr );
416
417         return $content;
418 }
419
420 /**
421  * Remove placeholders added by do_shortcodes_in_html_tags().
422  *
423  * @since 4.2.3
424  *
425  * @param string $content Content to search for placeholders.
426  * @return string Content with placeholders removed.
427  */
428 function unescape_invalid_shortcodes( $content ) {
429         // Clean up entire string, avoids re-parsing HTML.
430         $trans = array( '&#91;' => '[', '&#93;' => ']' );
431         $content = strtr( $content, $trans );
432
433         return $content;
434 }
435
436 /**
437  * Retrieve all attributes from the shortcodes tag.
438  *
439  * The attributes list has the attribute name as the key and the value of the
440  * attribute as the value in the key/value pair. This allows for easier
441  * retrieval of the attributes, since all attributes have to be known.
442  *
443  * @since 2.5.0
444  *
445  * @param string $text
446  * @return array List of attributes and their value.
447  */
448 function shortcode_parse_atts($text) {
449         $atts = array();
450         $pattern = '/([\w-]+)\s*=\s*"([^"]*)"(?:\s|$)|([\w-]+)\s*=\s*\'([^\']*)\'(?:\s|$)|([\w-]+)\s*=\s*([^\s\'"]+)(?:\s|$)|"([^"]*)"(?:\s|$)|(\S+)(?:\s|$)/';
451         $text = preg_replace("/[\x{00a0}\x{200b}]+/u", " ", $text);
452         if ( preg_match_all($pattern, $text, $match, PREG_SET_ORDER) ) {
453                 foreach ($match as $m) {
454                         if (!empty($m[1]))
455                                 $atts[strtolower($m[1])] = stripcslashes($m[2]);
456                         elseif (!empty($m[3]))
457                                 $atts[strtolower($m[3])] = stripcslashes($m[4]);
458                         elseif (!empty($m[5]))
459                                 $atts[strtolower($m[5])] = stripcslashes($m[6]);
460                         elseif (isset($m[7]) && strlen($m[7]))
461                                 $atts[] = stripcslashes($m[7]);
462                         elseif (isset($m[8]))
463                                 $atts[] = stripcslashes($m[8]);
464                 }
465
466                 // Reject any unclosed HTML elements
467                 foreach( $atts as &$value ) {
468                         if ( false !== strpos( $value, '<' ) ) {
469                                 if ( 1 !== preg_match( '/^[^<]*+(?:<[^>]*+>[^<]*+)*+$/', $value ) ) {
470                                         $value = '';
471                                 }
472                         }
473                 }
474         } else {
475                 $atts = ltrim($text);
476         }
477         return $atts;
478 }
479
480 /**
481  * Combine user attributes with known attributes and fill in defaults when needed.
482  *
483  * The pairs should be considered to be all of the attributes which are
484  * supported by the caller and given as a list. The returned attributes will
485  * only contain the attributes in the $pairs list.
486  *
487  * If the $atts list has unsupported attributes, then they will be ignored and
488  * removed from the final returned list.
489  *
490  * @since 2.5.0
491  *
492  * @param array  $pairs     Entire list of supported attributes and their defaults.
493  * @param array  $atts      User defined attributes in shortcode tag.
494  * @param string $shortcode Optional. The name of the shortcode, provided for context to enable filtering
495  * @return array Combined and filtered attribute list.
496  */
497 function shortcode_atts( $pairs, $atts, $shortcode = '' ) {
498         $atts = (array)$atts;
499         $out = array();
500         foreach($pairs as $name => $default) {
501                 if ( array_key_exists($name, $atts) )
502                         $out[$name] = $atts[$name];
503                 else
504                         $out[$name] = $default;
505         }
506         /**
507          * Filter a shortcode's default attributes.
508          *
509          * If the third parameter of the shortcode_atts() function is present then this filter is available.
510          * The third parameter, $shortcode, is the name of the shortcode.
511          *
512          * @since 3.6.0
513          *
514          * @param array $out   The output array of shortcode attributes.
515          * @param array $pairs The supported attributes and their defaults.
516          * @param array $atts  The user defined shortcode attributes.
517          */
518         if ( $shortcode )
519                 $out = apply_filters( "shortcode_atts_{$shortcode}", $out, $pairs, $atts );
520
521         return $out;
522 }
523
524 /**
525  * Remove all shortcode tags from the given content.
526  *
527  * @since 2.5.0
528  *
529  * @global array $shortcode_tags
530  *
531  * @param string $content Content to remove shortcode tags.
532  * @return string Content without shortcode tags.
533  */
534 function strip_shortcodes( $content ) {
535         global $shortcode_tags;
536
537         if ( false === strpos( $content, '[' ) ) {
538                 return $content;
539         }
540
541         if (empty($shortcode_tags) || !is_array($shortcode_tags))
542                 return $content;
543
544         $content = do_shortcodes_in_html_tags( $content, true );
545
546         $pattern = get_shortcode_regex();
547         $content = preg_replace_callback( "/$pattern/s", 'strip_shortcode_tag', $content );
548
549         // Always restore square braces so we don't break things like <!--[if IE ]>
550         $content = unescape_invalid_shortcodes( $content );
551
552         return $content;
553 }
554
555 /**
556  *
557  * @param array $m
558  * @return string|false
559  */
560 function strip_shortcode_tag( $m ) {
561         // allow [[foo]] syntax for escaping a tag
562         if ( $m[1] == '[' && $m[6] == ']' ) {
563                 return substr($m[0], 1, -1);
564         }
565
566         return $m[1] . $m[6];
567 }