Problem/Motivation

A fatal error occurs when trying to display a SVG image that does not exist when:

  • The field formatter is configured to display the SVG image inline;
  • And the module stage_file_proxy is enabled.

The following error gets logged:

ValueError: DOMDocument::loadXML(): Argument #1 ($source) must not be empty in DOMDocument->loadXML() (line 241 of /web/modules/contrib/svg_image_field/src/Plugin/Field/FieldFormatter/SvgImageFieldFormatter.php)

This situation can occur when putting a site locally: use a copy of the live database, but do not download all files (from sites/default/files) from the live site.

Steps to reproduce

  1. Enable modules svg_image_field, node and stage_file_proxy.
  2. Create a node type and add a field of type "svg_image_field" on it.
  3. On the display settings, for the svg field, choose the formatter "SVG Image Field formatter" and enable the option "Output SVG inline".
  4. Create a node and upload a SVG.
  5. Manually remove the SVG from the file system.
  6. Load the node page.

A fatal error occurs and the error noted above gets logged.

Proposed resolution

In SvgImageFieldFormatter there is a check if file exists before trying to display the image, but that check gets skipped when the stage_file_proxy module is enabled.
Add a check when the SVG file failed to load in memory before trying to pass it to DOMDocument::loadXML().

Remaining tasks

User interface changes

None.

API changes

None.

Data model changes

None.

A fix and tests will follow.

CommentFileSizeAuthor
#13 3333776-13-inline-svg-error.patch14.36 KBjwilson3
Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

MegaChriz created an issue. See original summary.

megachriz’s picture

Assigned: megachriz » Unassigned
Issue summary: View changes
Status: Active » Needs review

Code with a fix and tests are added in a MR. In order for the testbot to run the tests, branch tests would need to get enabled first on https://www.drupal.org/node/2863622/qa.

A merge request for 3333776-inline-svg-error-tests_only is only opened to be able to run tests on it and to demonstrate the issue, should branch tests get enabled.

jwilson3’s picture

I've enabled testing on the 2.2.x-dev branch, however we appear to currently have failing tests on the main branch that need to be resolved, before this test passes.

https://www.drupal.org/pift-ci-job/2570839

jwilson3’s picture

I've opened another issue to investigate and resolve the test failure, which blocks this issue.

#3334567: SVG Image Field: FileValidationTest.php:85 fails on invalid_svg1.svg

jwilson3’s picture

before I knew this issue existed, I took a slightly different approach to simply test whether the file existed before trying to get its contents.

diff --git a/src/Plugin/Field/FieldFormatter/SvgImageFieldFormatter.php b/src/Plugin/Field/FieldFormatter/SvgImageFieldFormatter.php
index a39d186..a726803 100644
--- a/src/Plugin/Field/FieldFormatter/SvgImageFieldFormatter.php
+++ b/src/Plugin/Field/FieldFormatter/SvgImageFieldFormatter.php
@@ -234,8 +234,11 @@ class SvgImageFieldFormatter extends FormatterBase implements ContainerFactoryPl
       }
       $svg_data = NULL;

-      if ($this->getSetting('inline')) {
-        $svg_file = file_get_contents($uri);
+      if (
+        $this->getSetting('inline') &&
+        is_file($uri) &&
+        $svg_file = file_get_contents($uri)
+      ) {
         $dom = new \DOMDocument();
         libxml_use_internal_errors(TRUE);
         $dom->loadXML($svg_file);

I'm not tied to either approach, but I do think that the warning string should be updated to not talk explicitly about file not being "downloaded", which could be confusing outside of the context of developers who know how stage_file_proxy works.

There may be other ways that a file could randomly go missing on a server, so I think a generic message of file not found could be helpful, or perhaps even no warning at all, and just silently render not SVG at all.

Tangentially, I'm actually wondering now how we could plug in to stage_file_proxy to further solve this issue in a better way and go download the image if it is missing. (I have Stage File Proxy configured -- i think correctly -- and it still doesnt seem to grab inline SVGs from PROD). Totally fine to separate that as a follow-up.

jwilson3’s picture

I rebased the MR so that the automated tests would run.

I also saw an underscore when doing a read through of the MR and wondered what it was, turns out it did cause a test failure:

Call to undefined method Drupal\Tests\svg_image_field\Functional\Plugin\Field\FieldFormatter\SvgImageFieldFormatterTest::_testDisplayMissingImageInline()

megachriz’s picture

Oops, I usually prefix test methods that I'm not currently interested in with an underscore, so that when running a test only the tests that don't start with an underscore run. A single functional test can easily run for a minute on my local machine, thus it can save a lot of time if I temporary disable some test methods. As soon as I'm done with all the tests, I remove the underscore prefixes again. But I see that I forgot to do that at one spot.

jwilson3’s picture

Assigned: Unassigned » jwilson3
Status: Needs review » Needs work

I usually prefix test methods that I'm not currently interested in with an underscore [...] As soon as I'm done with all the tests, I remove the underscore prefixes again. But I see that I forgot to do that at one spot.

Okay thanks. I'll update the code to remove the underscore.

I'm wondering how we could plug in to stage_file_proxy to further solve this issue in a better way and go download the image if it is missing.

I've investigated this. It appears that there is no way to get stage_file_proxy to download an image via its APIs/Classes/Class Methods except via the URL method. So what I propose is updating the logic to detect if the field formatter is is set to show SVGs inline, but the SVG file is missing or has empty content, then we could disable the inline setting for this image, which will make it fall back to using an <img> tag, whereby the URL request can be intercepted by Stage File Proxy via its normal method and downloaded to the server. Subsequent page loads after a cache clear would then be able to render the SVG inline once it finds it on the server. Note, the last step will only work if the Stage File Proxy "hotlinking" feature is disabled. With hotlinking enabled, the file is never downloaded to the server because the file URL is redirected to the proxy origin domain.

Working on finalizing the code changes and tests and will push a few commits shortly.

jwilson3’s picture

Nice. Tests pass. Now on to the remaining task from #10...

jwilson3’s picture

While manually testing this with and without stage file proxy, I'm seeing an issue when:

  • Stage File Proxy module is installed, but
  • file proxy functionality is disabled via settings.php $config overrides.

This is not an uncommon case for teams that leave stage_file_proxy module installed in all environments, and configure it for non-PROD environments in settings.local.php.

In this case I wasn't seeing the expected log error message in a simulated PROD configuration, alerting me to missing files.

jwilson3’s picture

Status: Needs work » Needs review
StatusFileSize
new14.36 KB

I've gotten this to a point where I'm more satisfied with the approach.

@MegaChriz resolved the primary issue here (the fatal error). However I wanted to improve integration with stage file proxy to see if we can actually download the missing files if that module is enabled.

My solution architecture is not a perfect solution because it takes 2 page loads in order to achieve a truly inline SVG display: The first request will fall back to an <img> tag, so that stage file proxy can download the file from the proxy origin. The second page load request will determine that the file exists on the server and load its contents as inline SVG.

I'm tempted to go ahead and commit but will wait one more day for code reviews and any feedback.

I'm also attaching a patch of the work to date, so I can use it and get this into a release I'm prepping so we can test in our remote CI environments.

Thanks @MegaChriz for opening this, providing patch and including tests! Kudos.

jwilson3’s picture

Assigned: jwilson3 » Unassigned
jwilson3’s picture

Issue summary: View changes
jwilson3’s picture

Title: Fatal error when trying to display inline a SVG image that does not exist and with stage_file_proxy module enabled » Add inline SVG support for stage_file_proxy

Update issue title to shorten commit message and coincide with updated scope.

megachriz’s picture

Manuel testing

I've tested the changes on a site. Works nice when not using the Hotlink feature from Stage File Proxy. When the Hotlink feature is used, the SVG is displayed as well, which I think is great! It is only not displayed inline - which I think makes sense. In this case though, the logs get spammed with warnings from SVG Image Field. That's less nice, but I guess also less of a concern for local or staging sites.

I was wondering if there is a simple way of downloading the SVG image field from the origin site and then display it inline even when the Hotlink feature is used. Maybe with an explicit http request? Would that trigger Stage File Proxy's ProxySubscriber? But perhaps we would be digging too much in what should be Stage File Proxy responsibility.

Code review

This mostly looks okay. I think that the warning message is a lot better then what I came up with :)

I did see one thing that I think could cause issues in the future:

In this codeblock, a value for $svg_file is defined.

      if (
        $this->getSetting('inline') &&
        (
          !is_file($uri) ||
          !$svg_file = @file_get_contents($uri)
        )
      ) {
        $this->setSetting('inline', FALSE);
        $this->logger->warning('Inline file %file is missing or empty. Inline display will be disabled and an image tag used instead.', ['%file' => $uri]);
      }

In the codeblock underneath, that variable is used:

      if ($this->getSetting('inline')) {
        $dom = new \DOMDocument();
        libxml_use_internal_errors(TRUE);
        $dom->loadXML($svg_file);
        if ($this->getSetting('force_fill')) {
          $dom->documentElement->setAttribute('fill', 'currentColor');
        }

If the conditions on the first code block would ever change, you could potentially get into a situation where $svg_file is not defined.

So, how the code is now is not wrong per se, but it creates a risk for future code changes. What I would do is trying to break up the method viewElements() into smaller pieces. All the code that's dealing with calculating the data to be displayed inline should then go into a separate method for example.
Perhaps the two code blocks mentioned above would then look something like this:

if ($this->getSetting('inline')) {
  if (!is_file($uri) || !$svg_file = @file_get_contents($uri)) {
    // (...)
  }
  else {
    $svg_data = $this->generateInlineSvg($svg_file);
  }
}

Maybe still not the most ideal, but at least the usage of $svg_file has become closer to where it gets defined.

I was thinking I would rather do something like this:

if ($this->getSetting('inline')) {
  $svg_file = @file_get_contents($uri)
  if (!is_file($uri) || !$svg_file) {
    // (...)
  }
  else {
    $svg_data = $this->generateInlineSvg($svg_file);
  }
}

But then there's a potential unnecessary file_get_contents() call.

megachriz’s picture

Or maybe the method generateInlineSvg() (mentioned in my previous comment) should receive $uri instead of $svg_file. In that case it could bail out if it receives something it cannot deal with. Something like this:

protected function generateInlineSvg(string $uri): ?string {
  if (!is_file($uri) || !$svg_file = @file_get_contents($uri)) {
    // (...)
    return NULL;
  }

  $dom = new \DOMDocument();
  libxml_use_internal_errors(TRUE);
  $dom->loadXML($svg_file);
  // (...)
}

Instead of returning NULL, it could also throw an exception maybe. Just some ideas!

jwilson3’s picture

Thanks for MR review; your feedback, insight and ideas on #17 and #18 are solid. What you propose about refactoring the inline rendering preparation tasks to a separate function or indenting things to me does make sense because the method is really really long. The $svg_file being assigned a value as part of an if clause, and then used later inside a different if clause is not the cleanest approach, to be sure.

I also debated some of these same things before ultimately deciding against a larger refactor in favor of adding the smallest bite-sized code change to keep the patch manageable, e.g. to not affect code indentation by gating everything inside an additional if.

I would be happy to review an updated MR with the changes you propose, as long as it does make things cleaner, if you want to take a stab. Otherwise I'm happy to leave this alone and get it in as is. Let me know if you want to pick it up. I do appreciate your time on this! Thanks

megachriz’s picture

I updated the code, made it somewhat cleaner.

There is now a method called generateInlineSvgData(). I added "Data" to the end, because its return value is going to be assigned to $element['#svg_data'] if it is not empty.

The inline setting check now looks as follows:

      // Set properties based on if the SVG is displayed inline or not.
      if ($this->getSetting('inline') && $svg_data = $this->generateInlineSvgData($uri, $attributes)) {
        $element['#inline'] = TRUE;
        $element['#svg_data'] = $svg_data;
      }
      else {
        $element['#inline'] = FALSE;
        $element['#uri'] = $uri;
      }

I thought about the following approach too, where #inline and #uri are set earlier and then overridden here:

      if ($this->getSetting('inline') && $svg_data = $this->generateInlineSvgData($uri, $attributes)) {
        $element['#inline'] = TRUE;
        $element['#uri'] = NULL;
        $element['#svg_data'] = $svg_data;
      }

I this case there is no else code block. I went the else block because then #uri didn't have to be set and unset again. I think an approach like that would make more sense if inline SVG image generation would have taken place in a subclass of SvgImageFieldFormatter. Then there would have been a method that would call the parent method if generating an inline SVG failed.

jwilson3’s picture

Status: Needs review » Needs work
  • A read through of the code changes looks good at first glance, haven't taken a chance to test this manually, and I do want to do that first.
  • I'd like to change the verb "generate" in the method signature to "load", which seems more accurate in this context.
  • Should we add the new #uri variable to the theme hook info?
  • Looks like the MR is no longer mergeable due to some issue queue activity from Martin merging in #3337975: DOMDocument::loadXML(): Argument #1 ($source) must not be empty. Apologies for dropping the ball — I got busy on other things. :( I still think this is the right approach for this issue, so we just need to manually merge with the latest dev branch.
jwilson3’s picture

megachriz’s picture

Status: Needs work » Needs review

I rebased the code on the latest 2.2.x. That was quite a thing! I hope I did it correctly. The rebase caused double moduleHandler code that I cleaned up in a new commit.

I'd like to change the verb "generate" in the method signature to "load", which seems more accurate in this context.

Method generateInlineSvgData() is renamed to loadInlineSvgData().

Should we add the new #uri variable to the theme hook info?

"uri" looks like to be already part of that:

/**
 * Implements hook_theme().
 */
function svg_image_field_theme() {
  return [
    'svg_image_field_formatter' => [
      'variables' => [
        'inline' => FALSE,
        'attributes' => NULL,
        'uri' => NULL,
        'svg_data' => NULL,
        'link_url' => NULL,
      ],
    ],
  ];
}

mandclu made their first commit to this issue’s fork.

  • jwilson3 committed f3cebd3c on 2.2.x authored by MegaChriz
    Issue #3333776 by MegaChriz, jwilson3: Improve stage_file_proxy module...
jwilson3’s picture

Status: Needs review » Fixed

Tested locally and confirmed the rebase is working correctly. Merged after a little bit of comment improvements.

Thanks @MegaChriz!

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.