Skip to content

Commit 3ee35eb

Browse files
jakejackson1claude
andauthored
Load a stylesheet url() with spaces, parentheses, inner quotes or an SVG data URI (#573)
A background image named in a stylesheet was not loaded when its local path had spaces or parentheses, when the url() had whitespace inside its parentheses, or when it was a percent-encoded SVG data URI such as Bootstrap's form-select arrow. - url() is read as CSS reads it, in either quote or unquoted. A backslash before a quote, a parenthesis or whitespace is dropped; other backslashes are kept for Windows paths. - A local path that is not found as written is tried percent-decoded. - A data: URI is no longer resolved against the base path, and one that is not base64 is decoded directly instead of through PHP's data: wrapper or the HTTP client. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent c06d6a7 commit 3ee35eb

9 files changed

Lines changed: 226 additions & 33 deletions

File tree

‎CHANGELOG-GRAVITYPDF.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,7 @@ Bugfixes
159159
* When a hyphenation hyphen moved to the next line, its record stayed on the line before. In a bidi paragraph that drew a hyphen in the wrong place and dropped the one that moved. [mpdf/mpdf#1831] [#145]
160160
* A hyphen inserted at a line break had no bidi direction. It now takes the direction of the word it breaks. [#116] [#137]
161161
* `$extgstates` had no default, so `count()` on it threw a `TypeError` on PHP 8. [mpdf/mpdf#2135] [#20]
162+
* A stylesheet `url()` did not load its image when the path had spaces or parentheses, when there was whitespace inside the parentheses, or when it was an SVG data URI that is not base64, such as Bootstrap's `form-select` arrow. [#573]
162163
* `linear-gradient(to bottom, …)` and `to top` were drawn upside down, and so was the vertical half of `to bottom right` and the other corners. Angles ran counter-clockwise from pointing right, so `90deg` drew bottom to top. A gradient now runs as CSS Images gives: `0deg` points up and angles turn clockwise, `turn` is read, and a corner keyword leaves the other two corners halfway along. `-moz-`, `-webkit-` and `-o-` gradients keep their legacy angles, and their side keyword, such as `left`, names the side the gradient starts from. [#577]
163164

164165
### Images and SVG
@@ -755,6 +756,7 @@ These changes do not change output.
755756
[#564]: https://github.com/GravityPDF/mpdf/pull/564
756757
[#563]: https://github.com/GravityPDF/mpdf/pull/563
757758
[#565]: https://github.com/GravityPDF/mpdf/pull/565
759+
[#573]: https://github.com/GravityPDF/mpdf/pull/573
758760
[#569]: https://github.com/GravityPDF/mpdf/pull/569
759761
[#577]: https://github.com/GravityPDF/mpdf/pull/577
760762
[#568]: https://github.com/GravityPDF/mpdf/pull/568

‎src/AssetFetcher.php‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,11 +66,14 @@ public function fetchLocalContent($path, $originalSrc)
6666
return $this->contentLoader->load($path);
6767
}
6868

69-
if ($path && $check = @fopen($path, 'rb')) {
70-
fclose($check);
71-
$this->logger->debug(sprintf('Fetching content of file "%s" with non-local basepath', $path), ['context' => LogContext::REMOTE_CONTENT]);
69+
// A path read from a URL, such as a stylesheet's url(), can carry percent-encoded spaces and parentheses
70+
foreach (array_unique([$path, rawurldecode($path)]) as $candidate) {
71+
if ($candidate && $check = @fopen($candidate, 'rb')) {
72+
fclose($check);
73+
$this->logger->debug(sprintf('Fetching content of file "%s" with non-local basepath', $candidate), ['context' => LogContext::REMOTE_CONTENT]);
7274

73-
return $this->contentLoader->load($path);
75+
return $this->contentLoader->load($candidate);
76+
}
7477
}
7578

7679
return $data;

‎src/Css/InlineStyleParser.php‎

Lines changed: 17 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -67,42 +67,32 @@ public function parse($html)
6767
}
6868

6969
/**
70-
* Process URLs in CSS strings by encoding special characters.
70+
* Rewrite each url() as url('...'), with the characters that would break the parsing after it encoded.
7171
*
72-
* Characters "(", ")", and ";" in url() can cause problems parsing CSS.
73-
* This method URLencodes ( and ), and temporarily encodes ";" to prevent
74-
* confusion with CSS segment delimiters.
72+
* The URL is read as CSS reads it: in either quote, with the other quote allowed inside, or unquoted, without the
73+
* whitespace around it. A backslash before a quote, a parenthesis or whitespace is dropped. Other backslashes
74+
* are kept, as a Windows path is full of them. Parentheses and braces are percent-encoded, and ";" becomes the
75+
* placeholder %ZZ, which the caller turns back once the declarations are split.
7576
*
7677
* @param string $css CSS string containing url() references
7778
* @return string CSS string with processed URLs
7879
*/
7980
public function processUrlsInCss($css)
8081
{
81-
if (strpos($css, 'url(') === false) {
82+
if (stripos($css, 'url(') === false) {
8283
return $css;
8384
}
8485

85-
// Process urls with double quotes
86-
preg_match_all('/url\(\"(.*?)\"\)/', $css, $m);
87-
foreach ($m[1] as $i => $url) {
88-
$tmp = str_replace(['(', ')', ';'], ['%28', '%29', '%ZZ'], $m[1][$i]);
89-
$css = str_replace($m[0][$i], 'url(\'' . $tmp . '\')', $css);
90-
}
91-
92-
// Process urls with single quotes
93-
preg_match_all('/url\(\'(.*?)\'\)/', $css, $m);
94-
foreach ($m[1] as $i => $url) {
95-
$tmp = str_replace(['(', ')', ';'], ['%28', '%29', '%ZZ'], $m[1][$i]);
96-
$css = str_replace($m[0][$i], 'url(\'' . $tmp . '\')', $css);
97-
}
98-
99-
// Process urls without quotes
100-
preg_match_all('/url\(([^\'\"].*?[^\'\"])\)/', $css, $m);
101-
foreach ($m[1] as $i => $url) {
102-
$tmp = str_replace(['(', ')', ';'], ['%28', '%29', '%ZZ'], $m[1][$i]);
103-
$css = str_replace($m[0][$i], 'url(\'' . $tmp . '\')', $css);
104-
}
105-
106-
return $css;
86+
// Possessive, so a long data URI does not run PCRE out of stack one character at a time
87+
return preg_replace_callback(
88+
'/url\(\s*(?:"((?:[^"\\\\]++|\\\\.)*+)"|\'((?:[^\'\\\\]++|\\\\.)*+)\'|((?:[^)\\\\]++|\\\\.)*+))\s*\)/is',
89+
function ($m) {
90+
$url = isset($m[3]) ? rtrim($m[3]) : (isset($m[2]) ? $m[2] : $m[1]);
91+
$url = preg_replace('/\\\\(["\'()\s])/', '$1', $url);
92+
93+
return "url('" . str_replace(['(', ')', '{', '}', ';'], ['%28', '%29', '%7B', '%7D', '%ZZ'], $url) . "')";
94+
},
95+
$css
96+
);
10797
}
10898
}

‎src/Image/ImageProcessor.php‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -147,9 +147,11 @@ public function getImage(&$file, $firstTime = true, $allowvector = true, $orig_s
147147
$file = md5($data);
148148
}
149149

150-
if (preg_match('/data:image\/(gif|jpe?g|png|webp|svg\+xml);base64,(.*)/', $file, $v)) {
150+
// Decoded here rather than through PHP's data: wrapper, which refuses a parameter such as ";utf8". A
151+
// percent-encoded SVG with "://" inside would otherwise be sent to the HTTP client
152+
if (preg_match('/data:image\/(gif|jpe?g|png|webp|svg\+xml)((?:;[^,;]+)*),(.*)/s', $file, $v)) {
151153
$type = $v[1];
152-
$data = base64_decode($v[2]);
154+
$data = preg_match('/;base64$/i', $v[2]) ? base64_decode($v[3]) : rawurldecode($v[3]);
153155
$file = md5($data);
154156
}
155157

‎src/Utils/Path.php‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,10 @@ class Path
1313
*/
1414
public static function relativeToAbsolutePath($relPath, $basePath)
1515
{
16+
if (stripos($relPath, 'data:') === 0) {
17+
return $relPath;
18+
}
19+
1620
// Fix Windows paths
1721
$relPath = str_replace("\\", '/', $relPath);
1822

‎tests/Mpdf/Css/InlineStyleParserTest.php‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,53 @@ public function testProcessUrls_WithParenthesesAndSemicolons()
7474
$this->assertStringNotContainsString('svg+xml;', $result);
7575
}
7676

77+
/**
78+
* Each url() is read as CSS reads it and written back single quoted, with the characters the parsing after it
79+
* splits on encoded
80+
*
81+
* @dataProvider urlProvider
82+
*
83+
* @param string $css
84+
* @param string $expected
85+
*/
86+
public function testProcessUrls($css, $expected)
87+
{
88+
$this->assertSame($expected, $this->inlineStyleParser->processUrlsInCss($css));
89+
}
90+
91+
/**
92+
* CSS with url() values, and what processUrlsInCss() makes of it
93+
*
94+
* @return array
95+
*/
96+
public function urlProvider()
97+
{
98+
$long = str_repeat('iVBORw0KGgo', 20000);
99+
100+
return [
101+
'double quotes with single quotes inside' => [
102+
'a { background: url("data:image/svg+xml,%3csvg xmlns=\'http://www.w3.org/2000/svg\'/%3e") }',
103+
'a { background: url(\'data:image/svg+xml,%3csvg xmlns=\'http://www.w3.org/2000/svg\'/%3e\') }',
104+
],
105+
'single quotes with double quotes inside' => [
106+
'a { background: url(\'data:image/svg+xml,%3csvg xmlns="http://www.w3.org/2000/svg"/%3e\') }',
107+
'a { background: url(\'data:image/svg+xml,%3csvg xmlns="http://www.w3.org/2000/svg"/%3e\') }',
108+
],
109+
'spaces and parentheses' => ['url("sub dir/im (1).png")', "url('sub dir/im %281%29.png')"],
110+
'whitespace around a quoted url' => ['url( "a.png" )', "url('a.png')"],
111+
'whitespace around an unquoted url' => ["url(\n a.png\t)", "url('a.png')"],
112+
'semicolon and braces' => ["url('data:image/svg+xml;utf8,<svg><style>p{}</style></svg>')", "url('data:image/svg+xml%ZZutf8,<svg><style>p%7B%7D</style></svg>')"],
113+
'escaped quote' => ['url("a\\"b.png")', "url('a\"b.png')"],
114+
'escaped parenthesis, unquoted' => ['url(a\\(1\\).png)', "url('a%281%29.png')"],
115+
'escaped space, unquoted' => ['url(a\\ b.png)', "url('a b.png')"],
116+
'Windows path' => ['url("D:\\a\\mpdf\\data\\img (1).png")', "url('D:\\a\\mpdf\\data\\img %281%29.png')"],
117+
'two urls' => ['url(a.png), url( "b c.png" )', "url('a.png'), url('b c.png')"],
118+
'upper case' => ['URL(a.png)', "url('a.png')"],
119+
'long quoted data URI' => ['url("data:image/png;base64,' . $long . '")', "url('data:image/png%ZZbase64," . $long . "')"],
120+
'long unquoted data URI' => ['url( data:image/png;base64,' . $long . ' )', "url('data:image/png%ZZbase64," . $long . "')"],
121+
];
122+
}
123+
77124
public function testParse_WithWebkitGradient()
78125
{
79126
$html = 'background: -webkit-gradient(linear, left top, left bottom, from(#ccc), to(#000));';

‎tests/Mpdf/StylesheetUrlTest.php‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
<?php
2+
3+
namespace Mpdf;
4+
5+
/**
6+
* A background image named in a stylesheet's url() loads whatever quoting, spacing and characters the URL is written
7+
* with, as it does in a browser.
8+
*/
9+
class StylesheetUrlTest extends \Yoast\PHPUnitPolyfills\TestCases\TestCase
10+
{
11+
12+
/**
13+
* Bootstrap 5's form-select arrow: double quoted, with single quotes, spaces and a "://" inside
14+
*/
15+
const BOOTSTRAP_ARROW = "data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23343a40' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='m2 5 6 6 6-6'/%3e%3c/svg%3e";
16+
17+
/**
18+
* @var string A directory holding "sub dir/bg (1).jpg"
19+
*/
20+
private $dir;
21+
22+
/**
23+
* Copy a test image to a name with a space and parentheses in it
24+
*/
25+
protected function set_up()
26+
{
27+
parent::set_up();
28+
29+
$this->dir = sys_get_temp_dir() . '/mpdf-url-' . uniqid() . '/';
30+
mkdir($this->dir . 'sub dir', 0777, true);
31+
copy(__DIR__ . '/../data/img/bg.jpg', $this->dir . 'sub dir/bg (1).jpg');
32+
}
33+
34+
/**
35+
* Remove the copied image
36+
*/
37+
protected function tear_down()
38+
{
39+
unlink($this->dir . 'sub dir/bg (1).jpg');
40+
rmdir($this->dir . 'sub dir');
41+
rmdir($this->dir);
42+
43+
parent::tear_down();
44+
}
45+
46+
/**
47+
* The background image loads, as a raster image or, for an SVG, a form XObject
48+
*
49+
* @dataProvider urlProvider
50+
*
51+
* @param string $url
52+
*/
53+
public function testBackgroundImageLoads($url)
54+
{
55+
foreach (['background-image: ' . $url, 'background: ' . $url . ' no-repeat'] as $declaration) {
56+
$mpdf = new Mpdf();
57+
$mpdf->SetBasePath($this->dir);
58+
$mpdf->WriteHTML('<style>div.bg { height: 20mm; ' . $declaration . '; }</style><div class="bg">x</div>');
59+
60+
$this->assertSame(1, count($mpdf->images) + count($mpdf->formobjects), $declaration);
61+
}
62+
}
63+
64+
/**
65+
* url() values that name an image
66+
*
67+
* @return array
68+
*/
69+
public function urlProvider()
70+
{
71+
return [
72+
'double quoted, space and parentheses' => ['url("sub dir/bg (1).jpg")'],
73+
'single quoted, space and parentheses' => ["url('sub dir/bg (1).jpg')"],
74+
'percent-encoded' => ['url(sub%20dir/bg%20%281%29.jpg)'],
75+
'whitespace inside the parentheses' => ['url( "sub dir/bg (1).jpg" )'],
76+
'unquoted, whitespace inside the parentheses' => ['url( sub%20dir/bg%20%281%29.jpg )'],
77+
'SVG data URI with single quotes inside' => ['url("' . self::BOOTSTRAP_ARROW . '")'],
78+
'SVG data URI with double quotes inside' => ["url('" . str_replace("'", '"', self::BOOTSTRAP_ARROW) . "')"],
79+
'SVG data URI with a ;utf8 parameter' => ['url("' . str_replace('svg+xml,', 'svg+xml;utf8,', self::BOOTSTRAP_ARROW) . '")'],
80+
];
81+
}
82+
83+
}
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
<?php
2+
3+
namespace Snapshots;
4+
5+
/**
6+
* Background images named in a stylesheet's url() with spaces, whitespace inside the parentheses, or quotes inside
7+
* the URL
8+
*
9+
* @group snapshot
10+
*/
11+
class StylesheetUrlSnapshotTest extends Snapshot
12+
{
13+
14+
/**
15+
* The fixture's name
16+
*
17+
* @return string
18+
*/
19+
public function getId()
20+
{
21+
return 'stylesheet-url';
22+
}
23+
24+
/**
25+
* Boxes with a background image each, under a caption saying what should be seen
26+
*/
27+
public function generatePdf()
28+
{
29+
$arrow = "data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23343a40' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='m2 5 6 6 6-6'/%3e%3c/svg%3e";
30+
31+
$html = '<style>
32+
body { font-size: 9pt; }
33+
h1 { font-size: 15pt; margin: 0 0 2mm 0; }
34+
p.caption { margin: 4mm 0 1mm 0; font-size: 8pt; color: #606060; }
35+
div.box { width: 70mm; height: 20mm; border: 0.2mm solid #999999; background-repeat: no-repeat; }
36+
div.spaced { background-image: url("img/bay eux.jpg"); }
37+
div.padded { background-image: url( img/bay%20eux.jpg ); }
38+
div.select { width: 60mm; height: 9mm; padding: 0 3mm; line-height: 9mm; background-image: url("' . $arrow . '"); background-position: right center; background-size: contain; }
39+
div.double { background-image: url(\'' . str_replace("'", '"', $arrow) . '\'); background-size: contain; background-position: center; }
40+
</style>
41+
42+
<h1>url() in a stylesheet</h1>
43+
44+
<p class="caption">url("img/bay eux.jpg"), with a space in the file name: the tapestry fills the box.</p>
45+
<div class="box spaced"></div>
46+
47+
<p class="caption">url( img/bay%20eux.jpg ), with whitespace inside the parentheses: the same tapestry.</p>
48+
<div class="box padded"></div>
49+
50+
<p class="caption">Bootstrap\'s form-select arrow, an SVG data URI with single quotes inside double quotes: a dark chevron at the right of the box.</p>
51+
<div class="box select">Choose</div>
52+
53+
<p class="caption">The same SVG with double quotes inside single quotes: a large chevron in the middle of the box.</p>
54+
<div class="box double"></div>';
55+
56+
$this->mpdf = $this->createMpdf();
57+
$this->mpdf->SetBasePath(__DIR__ . '/../data/');
58+
59+
$this->mpdf->WriteHTML($html);
60+
}
61+
62+
}
55.1 KB
Binary file not shown.

0 commit comments

Comments
 (0)