Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 

655 righe
20 KiB

  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. * @since 4.4.0 Added the `$tagnames` parameter.
  225. *
  226. * @global array $shortcode_tags
  227. *
  228. * @param array $tagnames Optional. List of shortcodes to find. Defaults to all registered shortcodes.
  229. * @return string The shortcode search regular expression
  230. */
  231. function get_shortcode_regex( $tagnames = null ) {
  232. global $shortcode_tags;
  233. if ( empty( $tagnames ) ) {
  234. $tagnames = array_keys( $shortcode_tags );
  235. }
  236. $tagregexp = join( '|', array_map('preg_quote', $tagnames) );
  237. // WARNING! Do not change this regex without changing do_shortcode_tag() and strip_shortcode_tag()
  238. // Also, see shortcode_unautop() and shortcode.js.
  239. return
  240. '\\[' // Opening bracket
  241. . '(\\[?)' // 1: Optional second opening bracket for escaping shortcodes: [[tag]]
  242. . "($tagregexp)" // 2: Shortcode name
  243. . '(?![\\w-])' // Not followed by word character or hyphen
  244. . '(' // 3: Unroll the loop: Inside the opening shortcode tag
  245. . '[^\\]\\/]*' // Not a closing bracket or forward slash
  246. . '(?:'
  247. . '\\/(?!\\])' // A forward slash not followed by a closing bracket
  248. . '[^\\]\\/]*' // Not a closing bracket or forward slash
  249. . ')*?'
  250. . ')'
  251. . '(?:'
  252. . '(\\/)' // 4: Self closing tag ...
  253. . '\\]' // ... and closing bracket
  254. . '|'
  255. . '\\]' // Closing bracket
  256. . '(?:'
  257. . '(' // 5: Unroll the loop: Optionally, anything between the opening and closing shortcode tags
  258. . '[^\\[]*+' // Not an opening bracket
  259. . '(?:'
  260. . '\\[(?!\\/\\2\\])' // An opening bracket not followed by the closing shortcode tag
  261. . '[^\\[]*+' // Not an opening bracket
  262. . ')*+'
  263. . ')'
  264. . '\\[\\/\\2\\]' // Closing shortcode tag
  265. . ')?'
  266. . ')'
  267. . '(\\]?)'; // 6: Optional second closing brocket for escaping shortcodes: [[tag]]
  268. }
  269. /**
  270. * Regular Expression callable for do_shortcode() for calling shortcode hook.
  271. * @see get_shortcode_regex for details of the match array contents.
  272. *
  273. * @since 2.5.0
  274. * @access private
  275. *
  276. * @global array $shortcode_tags
  277. *
  278. * @param array $m Regular expression match array
  279. * @return string|false False on failure.
  280. */
  281. function do_shortcode_tag( $m ) {
  282. global $shortcode_tags;
  283. // allow [[foo]] syntax for escaping a tag
  284. if ( $m[1] == '[' && $m[6] == ']' ) {
  285. return substr($m[0], 1, -1);
  286. }
  287. $tag = $m[2];
  288. $attr = shortcode_parse_atts( $m[3] );
  289. if ( ! is_callable( $shortcode_tags[ $tag ] ) ) {
  290. /* translators: %s: shortcode tag */
  291. $message = sprintf( __( 'Attempting to parse a shortcode without a valid callback: %s' ), $tag );
  292. _doing_it_wrong( __FUNCTION__, $message, '4.3.0' );
  293. return $m[0];
  294. }
  295. /**
  296. * Filters whether to call a shortcode callback.
  297. *
  298. * Passing a truthy value to the filter will effectively short-circuit the
  299. * shortcode generation process, returning that value instead.
  300. *
  301. * @since 4.7.0
  302. *
  303. * @param bool|string $return Short-circuit return value. Either false or the value to replace the shortcode with.
  304. * @param string $tag Shortcode name.
  305. * @param array $attr Shortcode attributes array,
  306. * @param array $m Regular expression match array.
  307. */
  308. $return = apply_filters( 'pre_do_shortcode_tag', false, $tag, $attr, $m );
  309. if ( false !== $return ) {
  310. return $return;
  311. }
  312. $content = isset( $m[5] ) ? $m[5] : null;
  313. $output = $m[1] . call_user_func( $shortcode_tags[ $tag ], $attr, $content, $tag ) . $m[6];
  314. /**
  315. * Filters the output created by a shortcode callback.
  316. *
  317. * @since 4.7.0
  318. *
  319. * @param string $output Shortcode output.
  320. * @param string $tag Shortcode name.
  321. * @param array $attr Shortcode attributes array,
  322. * @param array $m Regular expression match array.
  323. */
  324. return apply_filters( 'do_shortcode_tag', $output, $tag, $attr, $m );
  325. }
  326. /**
  327. * Search only inside HTML elements for shortcodes and process them.
  328. *
  329. * Any [ or ] characters remaining inside elements will be HTML encoded
  330. * to prevent interference with shortcodes that are outside the elements.
  331. * Assumes $content processed by KSES already. Users with unfiltered_html
  332. * capability may get unexpected output if angle braces are nested in tags.
  333. *
  334. * @since 4.2.3
  335. *
  336. * @param string $content Content to search for shortcodes
  337. * @param bool $ignore_html When true, all square braces inside elements will be encoded.
  338. * @param array $tagnames List of shortcodes to find.
  339. * @return string Content with shortcodes filtered out.
  340. */
  341. function do_shortcodes_in_html_tags( $content, $ignore_html, $tagnames ) {
  342. // Normalize entities in unfiltered HTML before adding placeholders.
  343. $trans = array( '&#91;' => '&#091;', '&#93;' => '&#093;' );
  344. $content = strtr( $content, $trans );
  345. $trans = array( '[' => '&#91;', ']' => '&#93;' );
  346. $pattern = get_shortcode_regex( $tagnames );
  347. $textarr = wp_html_split( $content );
  348. foreach ( $textarr as &$element ) {
  349. if ( '' == $element || '<' !== $element[0] ) {
  350. continue;
  351. }
  352. $noopen = false === strpos( $element, '[' );
  353. $noclose = false === strpos( $element, ']' );
  354. if ( $noopen || $noclose ) {
  355. // This element does not contain shortcodes.
  356. if ( $noopen xor $noclose ) {
  357. // Need to encode stray [ or ] chars.
  358. $element = strtr( $element, $trans );
  359. }
  360. continue;
  361. }
  362. if ( $ignore_html || '<!--' === substr( $element, 0, 4 ) || '<![CDATA[' === substr( $element, 0, 9 ) ) {
  363. // Encode all [ and ] chars.
  364. $element = strtr( $element, $trans );
  365. continue;
  366. }
  367. $attributes = wp_kses_attr_parse( $element );
  368. if ( false === $attributes ) {
  369. // Some plugins are doing things like [name] <[email]>.
  370. if ( 1 === preg_match( '%^<\s*\[\[?[^\[\]]+\]%', $element ) ) {
  371. $element = preg_replace_callback( "/$pattern/", 'do_shortcode_tag', $element );
  372. }
  373. // Looks like we found some crazy unfiltered HTML. Skipping it for sanity.
  374. $element = strtr( $element, $trans );
  375. continue;
  376. }
  377. // Get element name
  378. $front = array_shift( $attributes );
  379. $back = array_pop( $attributes );
  380. $matches = array();
  381. preg_match('%[a-zA-Z0-9]+%', $front, $matches);
  382. $elname = $matches[0];
  383. // Look for shortcodes in each attribute separately.
  384. foreach ( $attributes as &$attr ) {
  385. $open = strpos( $attr, '[' );
  386. $close = strpos( $attr, ']' );
  387. if ( false === $open || false === $close ) {
  388. continue; // Go to next attribute. Square braces will be escaped at end of loop.
  389. }
  390. $double = strpos( $attr, '"' );
  391. $single = strpos( $attr, "'" );
  392. if ( ( false === $single || $open < $single ) && ( false === $double || $open < $double ) ) {
  393. // $attr like '[shortcode]' or 'name = [shortcode]' implies unfiltered_html.
  394. // In this specific situation we assume KSES did not run because the input
  395. // was written by an administrator, so we should avoid changing the output
  396. // and we do not need to run KSES here.
  397. $attr = preg_replace_callback( "/$pattern/", 'do_shortcode_tag', $attr );
  398. } else {
  399. // $attr like 'name = "[shortcode]"' or "name = '[shortcode]'"
  400. // We do not know if $content was unfiltered. Assume KSES ran before shortcodes.
  401. $count = 0;
  402. $new_attr = preg_replace_callback( "/$pattern/", 'do_shortcode_tag', $attr, -1, $count );
  403. if ( $count > 0 ) {
  404. // Sanitize the shortcode output using KSES.
  405. $new_attr = wp_kses_one_attr( $new_attr, $elname );
  406. if ( '' !== trim( $new_attr ) ) {
  407. // The shortcode is safe to use now.
  408. $attr = $new_attr;
  409. }
  410. }
  411. }
  412. }
  413. $element = $front . implode( '', $attributes ) . $back;
  414. // Now encode any remaining [ or ] chars.
  415. $element = strtr( $element, $trans );
  416. }
  417. $content = implode( '', $textarr );
  418. return $content;
  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. return $content;
  433. }
  434. /**
  435. * Retrieve the shortcode attributes regex.
  436. *
  437. * @since 4.4.0
  438. *
  439. * @return string The shortcode attribute regular expression
  440. */
  441. function get_shortcode_atts_regex() {
  442. return '/([\w-]+)\s*=\s*"([^"]*)"(?:\s|$)|([\w-]+)\s*=\s*\'([^\']*)\'(?:\s|$)|([\w-]+)\s*=\s*([^\s\'"]+)(?:\s|$)|"([^"]*)"(?:\s|$)|(\S+)(?:\s|$)/';
  443. }
  444. /**
  445. * Retrieve all attributes from the shortcodes tag.
  446. *
  447. * The attributes list has the attribute name as the key and the value of the
  448. * attribute as the value in the key/value pair. This allows for easier
  449. * retrieval of the attributes, since all attributes have to be known.
  450. *
  451. * @since 2.5.0
  452. *
  453. * @param string $text
  454. * @return array|string List of attribute values.
  455. * Returns empty array if trim( $text ) == '""'.
  456. * Returns empty string if trim( $text ) == ''.
  457. * All other matches are checked for not empty().
  458. */
  459. function shortcode_parse_atts($text) {
  460. $atts = array();
  461. $pattern = get_shortcode_atts_regex();
  462. $text = preg_replace("/[\x{00a0}\x{200b}]+/u", " ", $text);
  463. if ( preg_match_all($pattern, $text, $match, PREG_SET_ORDER) ) {
  464. foreach ($match as $m) {
  465. if (!empty($m[1]))
  466. $atts[strtolower($m[1])] = stripcslashes($m[2]);
  467. elseif (!empty($m[3]))
  468. $atts[strtolower($m[3])] = stripcslashes($m[4]);
  469. elseif (!empty($m[5]))
  470. $atts[strtolower($m[5])] = stripcslashes($m[6]);
  471. elseif (isset($m[7]) && strlen($m[7]))
  472. $atts[] = stripcslashes($m[7]);
  473. elseif (isset($m[8]))
  474. $atts[] = stripcslashes($m[8]);
  475. }
  476. // Reject any unclosed HTML elements
  477. foreach( $atts as &$value ) {
  478. if ( false !== strpos( $value, '<' ) ) {
  479. if ( 1 !== preg_match( '/^[^<]*+(?:<[^>]*+>[^<]*+)*+$/', $value ) ) {
  480. $value = '';
  481. }
  482. }
  483. }
  484. } else {
  485. $atts = ltrim($text);
  486. }
  487. return $atts;
  488. }
  489. /**
  490. * Combine user attributes with known attributes and fill in defaults when needed.
  491. *
  492. * The pairs should be considered to be all of the attributes which are
  493. * supported by the caller and given as a list. The returned attributes will
  494. * only contain the attributes in the $pairs list.
  495. *
  496. * If the $atts list has unsupported attributes, then they will be ignored and
  497. * removed from the final returned list.
  498. *
  499. * @since 2.5.0
  500. *
  501. * @param array $pairs Entire list of supported attributes and their defaults.
  502. * @param array $atts User defined attributes in shortcode tag.
  503. * @param string $shortcode Optional. The name of the shortcode, provided for context to enable filtering
  504. * @return array Combined and filtered attribute list.
  505. */
  506. function shortcode_atts( $pairs, $atts, $shortcode = '' ) {
  507. $atts = (array)$atts;
  508. $out = array();
  509. foreach ($pairs as $name => $default) {
  510. if ( array_key_exists($name, $atts) )
  511. $out[$name] = $atts[$name];
  512. else
  513. $out[$name] = $default;
  514. }
  515. /**
  516. * Filters a shortcode's default attributes.
  517. *
  518. * If the third parameter of the shortcode_atts() function is present then this filter is available.
  519. * The third parameter, $shortcode, is the name of the shortcode.
  520. *
  521. * @since 3.6.0
  522. * @since 4.4.0 Added the `$shortcode` parameter.
  523. *
  524. * @param array $out The output array of shortcode attributes.
  525. * @param array $pairs The supported attributes and their defaults.
  526. * @param array $atts The user defined shortcode attributes.
  527. * @param string $shortcode The shortcode name.
  528. */
  529. if ( $shortcode ) {
  530. $out = apply_filters( "shortcode_atts_{$shortcode}", $out, $pairs, $atts, $shortcode );
  531. }
  532. return $out;
  533. }
  534. /**
  535. * Remove all shortcode tags from the given content.
  536. *
  537. * @since 2.5.0
  538. *
  539. * @global array $shortcode_tags
  540. *
  541. * @param string $content Content to remove shortcode tags.
  542. * @return string Content without shortcode tags.
  543. */
  544. function strip_shortcodes( $content ) {
  545. global $shortcode_tags;
  546. if ( false === strpos( $content, '[' ) ) {
  547. return $content;
  548. }
  549. if (empty($shortcode_tags) || !is_array($shortcode_tags))
  550. return $content;
  551. // Find all registered tag names in $content.
  552. preg_match_all( '@\[([^<>&/\[\]\x00-\x20=]++)@', $content, $matches );
  553. $tags_to_remove = array_keys( $shortcode_tags );
  554. /**
  555. * Filters the list of shortcode tags to remove from the content.
  556. *
  557. * @since 4.7.0
  558. *
  559. * @param array $tag_array Array of shortcode tags to remove.
  560. * @param string $content Content shortcodes are being removed from.
  561. */
  562. $tags_to_remove = apply_filters( 'strip_shortcodes_tagnames', $tags_to_remove, $content );
  563. $tagnames = array_intersect( $tags_to_remove, $matches[1] );
  564. if ( empty( $tagnames ) ) {
  565. return $content;
  566. }
  567. $content = do_shortcodes_in_html_tags( $content, true, $tagnames );
  568. $pattern = get_shortcode_regex( $tagnames );
  569. $content = preg_replace_callback( "/$pattern/", 'strip_shortcode_tag', $content );
  570. // Always restore square braces so we don't break things like <!--[if IE ]>
  571. $content = unescape_invalid_shortcodes( $content );
  572. return $content;
  573. }
  574. /**
  575. * Strips a shortcode tag based on RegEx matches against post content.
  576. *
  577. * @since 3.3.0
  578. *
  579. * @param array $m RegEx matches against post content.
  580. * @return string|false The content stripped of the tag, otherwise false.
  581. */
  582. function strip_shortcode_tag( $m ) {
  583. // allow [[foo]] syntax for escaping a tag
  584. if ( $m[1] == '[' && $m[6] == ']' ) {
  585. return substr($m[0], 1, -1);
  586. }
  587. return $m[1] . $m[6];
  588. }