From 16ab3fae648a5b7d36282666f8500487a94cb3a3 Mon Sep 17 00:00:00 2001 From: Sabina Talipova Date: Thu, 10 Aug 2023 12:45:52 +1200 Subject: [PATCH] FIX Double encoding image shortcode attributes --- src/Shortcodes/ImageShortcodeProvider.php | 21 ++++++++++- .../Shortcodes/ImageShortcodeProviderTest.php | 36 +++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/src/Shortcodes/ImageShortcodeProvider.php b/src/Shortcodes/ImageShortcodeProvider.php index f1afa112..b4b32f08 100644 --- a/src/Shortcodes/ImageShortcodeProvider.php +++ b/src/Shortcodes/ImageShortcodeProvider.php @@ -117,7 +117,7 @@ public static function handle_shortcode($args, $content, $parser, $shortcode, $e return in_array($k, $whitelist) && (strlen(trim($v ?? '')) || $k === 'alt'); }, ARRAY_FILTER_USE_BOTH); - $markup = HTML::createTag('img', $attrs); + $markup = self::createImageTag($attrs); // cache it for future reference if ($fileFound) { @@ -131,6 +131,25 @@ public static function handle_shortcode($args, $content, $parser, $shortcode, $e return $markup; } + /** + * Construct and return HTML image tag. + */ + public static function createImageTag(array $attributes) : string + { + $preparedAttributes = ''; + foreach ($attributes as $attributeKey => $attributeValue) { + if (strlen($attributeValue ?? '') > 0 || $attributeKey === 'alt') { + $preparedAttributes .= sprintf( + ' %s="%s"', + $attributeKey, + htmlspecialchars($attributeValue ?? '', ENT_QUOTES, 'UTF-8', false) + ); + } + } + + return ""; + } + /** * Regenerates "[image id=n]" shortcode with new src attribute prior to being edited within the CMS. * diff --git a/tests/php/Shortcodes/ImageShortcodeProviderTest.php b/tests/php/Shortcodes/ImageShortcodeProviderTest.php index 50a80d69..edca6579 100644 --- a/tests/php/Shortcodes/ImageShortcodeProviderTest.php +++ b/tests/php/Shortcodes/ImageShortcodeProviderTest.php @@ -338,4 +338,40 @@ public function testWhiteIsConfigurable() )) ); } + + public function gettersAndSettersProvider(): array + { + return [ + 'image without special characters' => [ + 'My alt text', + [ + 'src' => 'http://example.com/image.jpg', + 'alt' => 'My alt text', + 'title' => 'My Title', + 'width' => '300', + 'height' => '200', + 'class' => 'leftAlone ss-htmleditorfield-file image', + ], + ], + 'image with special characters' => [ + 'My alt text & special character', + [ + 'src' => 'http://example.com/image.jpg', + 'alt' => 'My alt text & special character', + 'title' => 'My Title & special character', + 'width' => '300', + 'height' => '200', + 'class' => 'leftAlone ss-htmleditorfield-file image', + ] + ] + ]; + } + + /** + * @dataProvider gettersAndSettersProvider + */ + public function testCreateImageTag(string $expected, array $attributes) + { + $this->assertEquals($expected, ImageShortcodeProvider::createImageTag($attributes)); + } }