Media image parsing broken by "loading" attribute

Created on 23 May 2023, over 1 year ago

Problem/Motivation

Image metatag (og:image in my case) includes an array of garbage data for media field images, becuse of the image loading attribute.

I have traced the problem to Drupal\metatag\Plugin\metatag\Tag::parseImageUrl()@547

if (strpos($value, '<img src="/') !== FALSE && strpos($value, '<img src="//') === FALSE) {
      $value = str_replace('<img src="/', '<img src="' . $base_root . '/', $value);
      $image_tag = TRUE;
}

where the code assumes that src would be the first attribute.

But the first attribute is actually loading, created by Drupal\media\Plugin\Field\FieldFormatter::viewElements()@157

$elements[$delta] = [
        '#theme' => 'image_formatter',
        '#item' => $media->get('thumbnail')->first(),
        '#item_attributes' => [
          'loading' => $this->getSetting('image_loading')['attribute'],
        ],
        '#image_style' => $this->getSetting('image_style'),
        '#url' => $this->getMediaThumbnailUrl($media, $items->getEntity()),
];

This makes metatag skip this and use the next parsing method

if ($image_tag) {
        preg_match_all('%\s*(|,\s*)(<\s*img\s+[^>]+>)%m', $value, $matches);
        $values = array_filter($matches[2] ?? []);
      }

...the workings of which I can't fully grasp ATM :) ...and produces additional tag values from the rest of the img tag. (e.g. alt content)

Steps to reproduce

This may be incomplete.

Create an image media type.
Create content media type, with a reference field to image media.
Set up metatag to generate (og:image) meta tag based on the image field ([node:field_image:entity:field_media_image])

In the case of og:image, the first tag finds the image, but there will be additional tags containing garbage data from the rest of the img tag (alt, title, class etc.)

Proposed resolution

The image url parser should not assume that src is the first attribute.

Remaining tasks

🐛 Bug report
Status

Active

Version

1.23

Component

Code

Created by

🇭🇺Hungary karol haltenberger

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024