PageRenderTime 43ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/shortcodes.php

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