PageRenderTime 51ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/shortcodes.php

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