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
- Enable modules svg_image_field, node and stage_file_proxy.
- Create a node type and add a field of type "svg_image_field" on it.
- On the display settings, for the svg field, choose the formatter "SVG Image Field formatter" and enable the option "Output SVG inline".
- Create a node and upload a SVG.
- Manually remove the SVG from the file system.
- 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
Add a fixAdd test coverageEnable automated testing for this project at https://www.drupal.org/node/2863622/qa so the provided tests can run here.- Review & commit
User interface changes
None.
API changes
None.
Data model changes
None.
A fix and tests will follow.
| Comment | File | Size | Author |
|---|---|---|---|
| #13 | 3333776-13-inline-svg-error.patch | 14.36 KB | jwilson3 |
Issue fork svg_image_field-3333776
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
Comment #4
megachrizCode 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.
Comment #5
jwilson3I'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
Comment #6
jwilson3I'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
Comment #7
jwilson3before I knew this issue existed, I took a slightly different approach to simply test whether the file existed before trying to get its contents.
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.
Comment #8
jwilson3I 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()Comment #9
megachrizOops, 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.
Comment #10
jwilson3Okay thanks. I'll update the code to remove the underscore.
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.
Comment #11
jwilson3Nice. Tests pass. Now on to the remaining task from #10...
Comment #12
jwilson3While manually testing this with and without stage file proxy, I'm seeing an issue when:
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.
Comment #13
jwilson3I'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.
Comment #14
jwilson3Comment #15
jwilson3Comment #16
jwilson3Update issue title to shorten commit message and coincide with updated scope.
Comment #17
megachrizManuel 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_fileis defined.In the codeblock underneath, that variable is used:
If the conditions on the first code block would ever change, you could potentially get into a situation where
$svg_fileis 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:
Maybe still not the most ideal, but at least the usage of
$svg_filehas become closer to where it gets defined.I was thinking I would rather do something like this:
But then there's a potential unnecessary
file_get_contents()call.Comment #18
megachrizOr maybe the method
generateInlineSvg()(mentioned in my previous comment) should receive$uriinstead of$svg_file. In that case it could bail out if it receives something it cannot deal with. Something like this:Instead of returning
NULL, it could also throw an exception maybe. Just some ideas!Comment #19
jwilson3Thanks 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
Comment #20
megachrizI 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:
I thought about the following approach too, where
#inlineand#uriare set earlier and then overridden here:I this case there is no
elsecode block. I went theelseblock because then#urididn'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.Comment #21
jwilson3Comment #22
jwilson3Comment #23
megachrizI 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.
Method
generateInlineSvgData()is renamed toloadInlineSvgData()."uri" looks like to be already part of that:
Comment #26
jwilson3Tested locally and confirmed the rebase is working correctly. Merged after a little bit of comment improvements.
Thanks @MegaChriz!