Opened 4 years ago
Last modified 4 years ago
#45929 new defect (bug)
Potential assignment to empty string
Reported by: |
|
Owned by: | |
---|---|---|---|
Milestone: | Awaiting Review | Priority: | normal |
Severity: | normal | Version: | 5.0.2 |
Component: | Shortcodes | Keywords: | |
Focuses: | Cc: |
Description
Some of WordPress's built-in shortcodes assume that the provided $attr
parameter
is an associative array. For instance, img_caption_shortcode
is currently
defined with the following code:
1489 /** 1490 * Builds the Caption shortcode output. [...] 1503 * @param array $attr { 1504 * Attributes of the caption shortcode. [...] 1516 */ 1517 function img_caption_shortcode( $attr, $content = null ) { 1518 // New-style shortcode with the caption inside the shortcode with the link and image tags. 1519 if ( ! isset( $attr['caption'] ) ) { 1520 if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) { 1521 $content = $matches[1]; 1522 $attr['caption'] = trim( $matches[2] ); 1523 } 1524 } elseif ( strpos( $attr['caption'], '<' ) !== false ) { 1525 $attr['caption'] = wp_kses( $attr['caption'], 'post' ); 1526 }
However, the shortcode parser can potentially return the empty string:
483 /** 484 * Retrieve all attributes from the shortcodes tag. [...] 493 * @return array|string List of attribute values. 494 * Returns empty array if trim( $text ) == '""'. 495 * Returns empty string if trim( $text ) == ''. 496 * All other matches are checked for not empty(). 497 */ 498 function shortcode_parse_atts( $text ) {
In PHP7, this behavior can cause problems for shortcodes which do not specify
any attributes. (Prior releases of PHP exposed surprising behavior for this case which averted the issue.)
To migrate my deployment to PHP7, I've preserved the behavior by overriding shortcodes on an as-needed basis:
function img_caption_shortcode_supporting_empty( $attr, $content = null ) {
if ( $attr == '' ) {
$attr = array();
}
return img_caption_shortcode($attr, $content);
}
remove_shortcode('caption');
add_shortcode('caption', 'img_caption_shortcode_supporting_empty');
But it seems like a few things should change in core:
- updating the documented type of the
$attr
parameter of shortcode functions - tolerating the empty string
Note: See
TracTickets for help on using
tickets.
Correction: the relevant change to PHP was in 7.1, not 7.0