wp/wp-includes/shortcodes.php
changeset 21 48c4eec2b7e6
parent 18 be944660c56a
--- a/wp/wp-includes/shortcodes.php	Thu Sep 29 08:06:27 2022 +0200
+++ b/wp/wp-includes/shortcodes.php	Fri Sep 05 18:40:08 2025 +0200
@@ -31,7 +31,7 @@
  */
 
 /**
- * Container for storing shortcode tags and their hook to call for the shortcode
+ * Container for storing shortcode tags and their hook to call for the shortcode.
  *
  * @since 2.5.0
  *
@@ -105,11 +105,10 @@
 }
 
 /**
- * Clear all shortcodes.
+ * Clears all shortcodes.
  *
- * This function is simple, it clears all of the shortcode tags by replacing the
- * shortcodes global by a empty array. This is actually a very efficient method
- * for removing all shortcodes.
+ * This function clears all of the shortcode tags by replacing the shortcodes global with
+ * an empty array. This is actually an efficient method for removing all shortcodes.
  *
  * @since 2.5.0
  *
@@ -122,7 +121,7 @@
 }
 
 /**
- * Whether a registered shortcode exists named $tag
+ * Determines whether a registered shortcode exists named $tag.
  *
  * @since 3.6.0
  *
@@ -137,7 +136,7 @@
 }
 
 /**
- * Whether the passed content contains the specified shortcode
+ * Determines whether the passed content contains the specified shortcode.
  *
  * @since 3.6.0
  *
@@ -148,7 +147,7 @@
  * @return bool Whether the passed content contains the given shortcode.
  */
 function has_shortcode( $content, $tag ) {
-	if ( false === strpos( $content, '[' ) ) {
+	if ( ! str_contains( $content, '[' ) ) {
 		return false;
 	}
 
@@ -170,7 +169,45 @@
 }
 
 /**
- * Search content for shortcodes and filter shortcodes through their hooks.
+ * Returns a list of registered shortcode names found in the given content.
+ *
+ * Example usage:
+ *
+ *     get_shortcode_tags_in_content( '[audio src="file.mp3"][/audio] [foo] [gallery ids="1,2,3"]' );
+ *     // array( 'audio', 'gallery' )
+ *
+ * @since 6.3.2
+ *
+ * @param string $content The content to check.
+ * @return string[] An array of registered shortcode names found in the content.
+ */
+function get_shortcode_tags_in_content( $content ) {
+	if ( false === strpos( $content, '[' ) ) {
+		return array();
+	}
+
+	preg_match_all( '/' . get_shortcode_regex() . '/', $content, $matches, PREG_SET_ORDER );
+	if ( empty( $matches ) ) {
+		return array();
+	}
+
+	$tags = array();
+	foreach ( $matches as $shortcode ) {
+		$tags[] = $shortcode[2];
+
+		if ( ! empty( $shortcode[5] ) ) {
+			$deep_tags = get_shortcode_tags_in_content( $shortcode[5] );
+			if ( ! empty( $deep_tags ) ) {
+				$tags = array_merge( $tags, $deep_tags );
+			}
+		}
+	}
+
+	return $tags;
+}
+
+/**
+ * Searches content for shortcodes and filter shortcodes through their hooks.
  *
  * This function is an alias for do_shortcode().
  *
@@ -188,7 +225,7 @@
 }
 
 /**
- * Search content for shortcodes and filter shortcodes through their hooks.
+ * Searches content for shortcodes and filter shortcodes through their hooks.
  *
  * If there are no shortcode tags defined, then the content will be returned
  * without any filtering. This might cause issues when plugins are disabled but
@@ -206,7 +243,7 @@
 function do_shortcode( $content, $ignore_html = false ) {
 	global $shortcode_tags;
 
-	if ( false === strpos( $content, '[' ) ) {
+	if ( ! str_contains( $content, '[' ) ) {
 		return $content;
 	}
 
@@ -222,6 +259,14 @@
 		return $content;
 	}
 
+	// Ensure this context is only added once if shortcodes are nested.
+	$has_filter   = has_filter( 'wp_get_attachment_image_context', '_filter_do_shortcode_context' );
+	$filter_added = false;
+
+	if ( ! $has_filter ) {
+		$filter_added = add_filter( 'wp_get_attachment_image_context', '_filter_do_shortcode_context' );
+	}
+
 	$content = do_shortcodes_in_html_tags( $content, $ignore_html, $tagnames );
 
 	$pattern = get_shortcode_regex( $tagnames );
@@ -230,11 +275,31 @@
 	// Always restore square braces so we don't break things like <!--[if IE ]>.
 	$content = unescape_invalid_shortcodes( $content );
 
+	// Only remove the filter if it was added in this scope.
+	if ( $filter_added ) {
+		remove_filter( 'wp_get_attachment_image_context', '_filter_do_shortcode_context' );
+	}
+
 	return $content;
 }
 
 /**
- * Retrieve the shortcode regular expression for searching.
+ * Filter the `wp_get_attachment_image_context` hook during shortcode rendering.
+ *
+ * When wp_get_attachment_image() is called during shortcode rendering, we need to make clear
+ * that the context is a shortcode and not part of the theme's template rendering logic.
+ *
+ * @since 6.3.0
+ * @access private
+ *
+ * @return string The filtered context value for wp_get_attachment_images when doing shortcodes.
+ */
+function _filter_do_shortcode_context() {
+	return 'do_shortcode';
+}
+
+/**
+ * Retrieves the shortcode regular expression for searching.
  *
  * The regular expression combines the shortcode tags in the regular expression
  * in a regex class.
@@ -264,8 +329,10 @@
 	}
 	$tagregexp = implode( '|', array_map( 'preg_quote', $tagnames ) );
 
-	// WARNING! Do not change this regex without changing do_shortcode_tag() and strip_shortcode_tag().
-	// Also, see shortcode_unautop() and shortcode.js.
+	/*
+	 * WARNING! Do not change this regex without changing do_shortcode_tag() and strip_shortcode_tag().
+	 * Also, see shortcode_unautop() and shortcode.js.
+	 */
 
 	// phpcs:disable Squiz.Strings.ConcatenationSpacing.PaddingFound -- don't remove regex indentation
 	return '\\['                             // Opening bracket.
@@ -295,7 +362,7 @@
 		.         '\\[\\/\\2\\]'             // Closing shortcode tag.
 		.     ')?'
 		. ')'
-		. '(\\]?)';                          // 6: Optional second closing brocket for escaping shortcodes: [[tag]].
+		. '(\\]?)';                          // 6: Optional second closing bracket for escaping shortcodes: [[tag]].
 	// phpcs:enable
 }
 
@@ -309,8 +376,18 @@
  *
  * @global array $shortcode_tags
  *
- * @param array $m Regular expression match array.
- * @return string|false Shortcode output on success, false on failure.
+ * @param array $m {
+ *     Regular expression match array.
+ *
+ *     @type string $0 Entire matched shortcode text.
+ *     @type string $1 Optional second opening bracket for escaping shortcodes.
+ *     @type string $2 Shortcode name.
+ *     @type string $3 Shortcode arguments list.
+ *     @type string $4 Optional self closing slash.
+ *     @type string $5 Content of a shortcode when it wraps some content.
+ *     @type string $6 Optional second closing bracket for escaping shortcodes.
+ * }
+ * @return string Shortcode output.
  */
 function do_shortcode_tag( $m ) {
 	global $shortcode_tags;
@@ -340,11 +417,12 @@
 	 * shortcode generation process, returning that value instead.
 	 *
 	 * @since 4.7.0
+	 * @since 6.5.0 The `$attr` parameter is always an array.
 	 *
-	 * @param false|string $return      Short-circuit return value. Either false or the value to replace the shortcode with.
-	 * @param string       $tag         Shortcode name.
-	 * @param array|string $attr        Shortcode attributes array or empty string.
-	 * @param array        $m           Regular expression match array.
+	 * @param false|string $output Short-circuit return value. Either false or the value to replace the shortcode with.
+	 * @param string       $tag    Shortcode name.
+	 * @param array        $attr   Shortcode attributes array, can be empty if the original arguments string cannot be parsed.
+	 * @param array        $m      Regular expression match array.
 	 */
 	$return = apply_filters( 'pre_do_shortcode_tag', false, $tag, $attr, $m );
 	if ( false !== $return ) {
@@ -359,17 +437,18 @@
 	 * Filters the output created by a shortcode callback.
 	 *
 	 * @since 4.7.0
+	 * @since 6.5.0 The `$attr` parameter is always an array.
 	 *
-	 * @param string       $output Shortcode output.
-	 * @param string       $tag    Shortcode name.
-	 * @param array|string $attr   Shortcode attributes array or empty string.
-	 * @param array        $m      Regular expression match array.
+	 * @param string $output Shortcode output.
+	 * @param string $tag    Shortcode name.
+	 * @param array  $attr   Shortcode attributes array, can be empty if the original arguments string cannot be parsed.
+	 * @param array  $m      Regular expression match array.
 	 */
 	return apply_filters( 'do_shortcode_tag', $output, $tag, $attr, $m );
 }
 
 /**
- * Search only inside HTML elements for shortcodes and process them.
+ * Searches only inside HTML elements for shortcodes and process them.
  *
  * Any [ or ] characters remaining inside elements will be HTML encoded
  * to prevent interference with shortcodes that are outside the elements.
@@ -403,8 +482,8 @@
 			continue;
 		}
 
-		$noopen  = false === strpos( $element, '[' );
-		$noclose = false === strpos( $element, ']' );
+		$noopen  = ! str_contains( $element, '[' );
+		$noclose = ! str_contains( $element, ']' );
 		if ( $noopen || $noclose ) {
 			// This element does not contain shortcodes.
 			if ( $noopen xor $noclose ) {
@@ -414,7 +493,7 @@
 			continue;
 		}
 
-		if ( $ignore_html || '<!--' === substr( $element, 0, 4 ) || '<![CDATA[' === substr( $element, 0, 9 ) ) {
+		if ( $ignore_html || str_starts_with( $element, '<!--' ) || str_starts_with( $element, '<![CDATA[' ) ) {
 			// Encode all '[' and ']' chars.
 			$element = strtr( $element, $trans );
 			continue;
@@ -427,7 +506,7 @@
 				$element = preg_replace_callback( "/$pattern/", 'do_shortcode_tag', $element );
 			}
 
-			// Looks like we found some crazy unfiltered HTML. Skipping it for sanity.
+			// Looks like we found some unexpected unfiltered HTML. Skipping it for confidence.
 			$element = strtr( $element, $trans );
 			continue;
 		}
@@ -457,8 +536,10 @@
 				 */
 				$attr = preg_replace_callback( "/$pattern/", 'do_shortcode_tag', $attr );
 			} else {
-				// $attr like 'name = "[shortcode]"' or "name = '[shortcode]'".
-				// We do not know if $content was unfiltered. Assume KSES ran before shortcodes.
+				/*
+				 * $attr like 'name = "[shortcode]"' or "name = '[shortcode]'".
+				 * We do not know if $content was unfiltered. Assume KSES ran before shortcodes.
+				 */
 				$count    = 0;
 				$new_attr = preg_replace_callback( "/$pattern/", 'do_shortcode_tag', $attr, -1, $count );
 				if ( $count > 0 ) {
@@ -483,7 +564,7 @@
 }
 
 /**
- * Remove placeholders added by do_shortcodes_in_html_tags().
+ * Removes placeholders added by do_shortcodes_in_html_tags().
  *
  * @since 4.2.3
  *
@@ -503,30 +584,31 @@
 }
 
 /**
- * Retrieve the shortcode attributes regex.
+ * Retrieves the shortcode attributes regex.
  *
  * @since 4.4.0
  *
- * @return string The shortcode attribute regular expression
+ * @return string The shortcode attribute regular expression.
  */
 function get_shortcode_atts_regex() {
 	return '/([\w-]+)\s*=\s*"([^"]*)"(?:\s|$)|([\w-]+)\s*=\s*\'([^\']*)\'(?:\s|$)|([\w-]+)\s*=\s*([^\s\'"]+)(?:\s|$)|"([^"]*)"(?:\s|$)|\'([^\']*)\'(?:\s|$)|(\S+)(?:\s|$)/';
 }
 
 /**
- * Retrieve all attributes from the shortcodes tag.
+ * Retrieves all attributes from the shortcodes tag.
  *
  * The attributes list has the attribute name as the key and the value of the
  * attribute as the value in the key/value pair. This allows for easier
  * retrieval of the attributes, since all attributes have to be known.
  *
  * @since 2.5.0
+ * @since 6.5.0 The function now always returns an array,
+ *              even if the original arguments string cannot be parsed or is empty.
  *
- * @param string $text
- * @return array|string List of attribute values.
- *                      Returns empty array if '""' === trim( $text ).
- *                      Returns empty string if '' === trim( $text ).
- *                      All other matches are checked for not empty().
+ * @param string $text Shortcode arguments list.
+ * @return array Array of attribute values keyed by attribute name.
+ *               Returns empty array if there are no attributes
+ *               or if the original arguments string cannot be parsed.
  */
 function shortcode_parse_atts( $text ) {
 	$atts    = array();
@@ -551,21 +633,19 @@
 
 		// Reject any unclosed HTML elements.
 		foreach ( $atts as &$value ) {
-			if ( false !== strpos( $value, '<' ) ) {
+			if ( str_contains( $value, '<' ) ) {
 				if ( 1 !== preg_match( '/^[^<]*+(?:<[^>]*+>[^<]*+)*+$/', $value ) ) {
 					$value = '';
 				}
 			}
 		}
-	} else {
-		$atts = ltrim( $text );
 	}
 
 	return $atts;
 }
 
 /**
- * Combine user attributes with known attributes and fill in defaults when needed.
+ * Combines user attributes with known attributes and fill in defaults when needed.
  *
  * The pairs should be considered to be all of the attributes which are
  * supported by the caller and given as a list. The returned attributes will
@@ -614,7 +694,7 @@
 }
 
 /**
- * Remove all shortcode tags from the given content.
+ * Removes all shortcode tags from the given content.
  *
  * @since 2.5.0
  *
@@ -626,7 +706,7 @@
 function strip_shortcodes( $content ) {
 	global $shortcode_tags;
 
-	if ( false === strpos( $content, '[' ) ) {
+	if ( ! str_contains( $content, '[' ) ) {
 		return $content;
 	}