Skip to content

Commit

Permalink
BUG Cast image dimensions from shortcode as int to avoid exception wh…
Browse files Browse the repository at this point in the history
…en dimensions are not numeric (#436)

* Cast image dimensions from shortcode as int

This prevents sizes like '50%' from triggering exceptions.
Fixes #434 (or at least prevents an exception)

* Add a test for non-integer imagesize handling in shortcodes

Quick/first attempt...

* Escape legit percent sign in sprintf string

Co-authored-by: Maxime Rainville <maxime@rainville.me>
  • Loading branch information
micschk and maxime-rainville committed Mar 1, 2021
1 parent 3535311 commit 4018329
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/Shortcodes/ImageShortcodeProvider.php
Expand Up @@ -73,8 +73,8 @@ public static function handle_shortcode($args, $content, $parser, $shortcode, $e
// Check if a resize is required
$src = $record->getURL($allowSessionGrant);
if ($record instanceof Image) {
$width = isset($args['width']) ? $args['width'] : null;
$height = isset($args['height']) ? $args['height'] : null;
$width = isset($args['width']) ? (int) $args['width'] : null;
$height = isset($args['height']) ? (int) $args['height'] : null;
$hasCustomDimensions = ($width && $height);
if ($hasCustomDimensions && (($width != $record->getWidth()) || ($height != $record->getHeight()))) {
$resized = $record->ResizedImage($width, $height);
Expand Down
18 changes: 18 additions & 0 deletions tests/php/Shortcodes/ImageShortcodeProviderTest.php
Expand Up @@ -89,6 +89,24 @@ public function testShortcodeHandlerAddsDefaultAttributes()
))
);
}

public function testShortcodeHandlerDoesNotResampleToNonIntegerImagesSizes()
{
$image = $this->objFromFixture(Image::class, 'imageWithoutTitle');
$parser = new ShortcodeParser();
$parser->register('image', [ImageShortcodeProvider::class, 'handle_shortcode']);

$this->assertEquals(
sprintf(
'<img src="%s" alt="" width="50%%" height="auto">',
$image->Link()
),
$parser->parse(sprintf(
'[image id="%d" alt="" width="50%%" height="auto"]',
$image->ID
))
);
}

public function testShortcodeHandlerFailsGracefully()
{
Expand Down

0 comments on commit 4018329

Please sign in to comment.