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