Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG-GRAVITYPDF.md
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ Bugfixes
* 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]
* A hyphen inserted at a line break had no bidi direction. It now takes the direction of the word it breaks. [#116] [#137]
* `$extgstates` had no default, so `count()` on it threw a `TypeError` on PHP 8. [mpdf/mpdf#2135] [#20]
* 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]
* `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]

### Images and SVG
Expand Down Expand Up @@ -755,6 +756,7 @@ These changes do not change output.
[#564]: https://github.com/GravityPDF/mpdf/pull/564
[#563]: https://github.com/GravityPDF/mpdf/pull/563
[#565]: https://github.com/GravityPDF/mpdf/pull/565
[#573]: https://github.com/GravityPDF/mpdf/pull/573
[#569]: https://github.com/GravityPDF/mpdf/pull/569
[#577]: https://github.com/GravityPDF/mpdf/pull/577
[#568]: https://github.com/GravityPDF/mpdf/pull/568
Expand Down
11 changes: 7 additions & 4 deletions src/AssetFetcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,14 @@ public function fetchLocalContent($path, $originalSrc)
return $this->contentLoader->load($path);
}

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

return $this->contentLoader->load($path);
return $this->contentLoader->load($candidate);
}
}

return $data;
Expand Down
44 changes: 17 additions & 27 deletions src/Css/InlineStyleParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,42 +67,32 @@ public function parse($html)
}

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

// Process urls with double quotes
preg_match_all('/url\(\"(.*?)\"\)/', $css, $m);
foreach ($m[1] as $i => $url) {
$tmp = str_replace(['(', ')', ';'], ['%28', '%29', '%ZZ'], $m[1][$i]);
$css = str_replace($m[0][$i], 'url(\'' . $tmp . '\')', $css);
}

// Process urls with single quotes
preg_match_all('/url\(\'(.*?)\'\)/', $css, $m);
foreach ($m[1] as $i => $url) {
$tmp = str_replace(['(', ')', ';'], ['%28', '%29', '%ZZ'], $m[1][$i]);
$css = str_replace($m[0][$i], 'url(\'' . $tmp . '\')', $css);
}

// Process urls without quotes
preg_match_all('/url\(([^\'\"].*?[^\'\"])\)/', $css, $m);
foreach ($m[1] as $i => $url) {
$tmp = str_replace(['(', ')', ';'], ['%28', '%29', '%ZZ'], $m[1][$i]);
$css = str_replace($m[0][$i], 'url(\'' . $tmp . '\')', $css);
}

return $css;
// Possessive, so a long data URI does not run PCRE out of stack one character at a time
return preg_replace_callback(
'/url\(\s*(?:"((?:[^"\\\\]++|\\\\.)*+)"|\'((?:[^\'\\\\]++|\\\\.)*+)\'|((?:[^)\\\\]++|\\\\.)*+))\s*\)/is',
function ($m) {
$url = isset($m[3]) ? rtrim($m[3]) : (isset($m[2]) ? $m[2] : $m[1]);
$url = preg_replace('/\\\\(["\'()\s])/', '$1', $url);

return "url('" . str_replace(['(', ')', '{', '}', ';'], ['%28', '%29', '%7B', '%7D', '%ZZ'], $url) . "')";
},
$css
);
}
}
6 changes: 4 additions & 2 deletions src/Image/ImageProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -147,9 +147,11 @@ public function getImage(&$file, $firstTime = true, $allowvector = true, $orig_s
$file = md5($data);
}

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

Expand Down
4 changes: 4 additions & 0 deletions src/Utils/Path.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ class Path
*/
public static function relativeToAbsolutePath($relPath, $basePath)
{
if (stripos($relPath, 'data:') === 0) {
return $relPath;
}

// Fix Windows paths
$relPath = str_replace("\\", '/', $relPath);

Expand Down
47 changes: 47 additions & 0 deletions tests/Mpdf/Css/InlineStyleParserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,53 @@ public function testProcessUrls_WithParenthesesAndSemicolons()
$this->assertStringNotContainsString('svg+xml;', $result);
}

/**
* Each url() is read as CSS reads it and written back single quoted, with the characters the parsing after it
* splits on encoded
*
* @dataProvider urlProvider
*
* @param string $css
* @param string $expected
*/
public function testProcessUrls($css, $expected)
{
$this->assertSame($expected, $this->inlineStyleParser->processUrlsInCss($css));
}

/**
* CSS with url() values, and what processUrlsInCss() makes of it
*
* @return array
*/
public function urlProvider()
{
$long = str_repeat('iVBORw0KGgo', 20000);

return [
'double quotes with single quotes inside' => [
'a { background: url("data:image/svg+xml,%3csvg xmlns=\'http://www.w3.org/2000/svg\'/%3e") }',
'a { background: url(\'data:image/svg+xml,%3csvg xmlns=\'http://www.w3.org/2000/svg\'/%3e\') }',
],
'single quotes with double quotes inside' => [
'a { background: url(\'data:image/svg+xml,%3csvg xmlns="http://www.w3.org/2000/svg"/%3e\') }',
'a { background: url(\'data:image/svg+xml,%3csvg xmlns="http://www.w3.org/2000/svg"/%3e\') }',
],
'spaces and parentheses' => ['url("sub dir/im (1).png")', "url('sub dir/im %281%29.png')"],
'whitespace around a quoted url' => ['url( "a.png" )', "url('a.png')"],
'whitespace around an unquoted url' => ["url(\n a.png\t)", "url('a.png')"],
'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>')"],
'escaped quote' => ['url("a\\"b.png")', "url('a\"b.png')"],
'escaped parenthesis, unquoted' => ['url(a\\(1\\).png)', "url('a%281%29.png')"],
'escaped space, unquoted' => ['url(a\\ b.png)', "url('a b.png')"],
'Windows path' => ['url("D:\\a\\mpdf\\data\\img (1).png")', "url('D:\\a\\mpdf\\data\\img %281%29.png')"],
'two urls' => ['url(a.png), url( "b c.png" )', "url('a.png'), url('b c.png')"],
'upper case' => ['URL(a.png)', "url('a.png')"],
'long quoted data URI' => ['url("data:image/png;base64,' . $long . '")', "url('data:image/png%ZZbase64," . $long . "')"],
'long unquoted data URI' => ['url( data:image/png;base64,' . $long . ' )', "url('data:image/png%ZZbase64," . $long . "')"],
];
}

public function testParse_WithWebkitGradient()
{
$html = 'background: -webkit-gradient(linear, left top, left bottom, from(#ccc), to(#000));';
Expand Down
83 changes: 83 additions & 0 deletions tests/Mpdf/StylesheetUrlTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?php

namespace Mpdf;

/**
* A background image named in a stylesheet's url() loads whatever quoting, spacing and characters the URL is written
* with, as it does in a browser.
*/
class StylesheetUrlTest extends \Yoast\PHPUnitPolyfills\TestCases\TestCase
{

/**
* Bootstrap 5's form-select arrow: double quoted, with single quotes, spaces and a "://" inside
*/
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";

/**
* @var string A directory holding "sub dir/bg (1).jpg"
*/
private $dir;

/**
* Copy a test image to a name with a space and parentheses in it
*/
protected function set_up()
{
parent::set_up();

$this->dir = sys_get_temp_dir() . '/mpdf-url-' . uniqid() . '/';
mkdir($this->dir . 'sub dir', 0777, true);
copy(__DIR__ . '/../data/img/bg.jpg', $this->dir . 'sub dir/bg (1).jpg');
}

/**
* Remove the copied image
*/
protected function tear_down()
{
unlink($this->dir . 'sub dir/bg (1).jpg');
rmdir($this->dir . 'sub dir');
rmdir($this->dir);

parent::tear_down();
}

/**
* The background image loads, as a raster image or, for an SVG, a form XObject
*
* @dataProvider urlProvider
*
* @param string $url
*/
public function testBackgroundImageLoads($url)
{
foreach (['background-image: ' . $url, 'background: ' . $url . ' no-repeat'] as $declaration) {
$mpdf = new Mpdf();
$mpdf->SetBasePath($this->dir);
$mpdf->WriteHTML('<style>div.bg { height: 20mm; ' . $declaration . '; }</style><div class="bg">x</div>');

$this->assertSame(1, count($mpdf->images) + count($mpdf->formobjects), $declaration);
}
}

/**
* url() values that name an image
*
* @return array
*/
public function urlProvider()
{
return [
'double quoted, space and parentheses' => ['url("sub dir/bg (1).jpg")'],
'single quoted, space and parentheses' => ["url('sub dir/bg (1).jpg')"],
'percent-encoded' => ['url(sub%20dir/bg%20%281%29.jpg)'],
'whitespace inside the parentheses' => ['url( "sub dir/bg (1).jpg" )'],
'unquoted, whitespace inside the parentheses' => ['url( sub%20dir/bg%20%281%29.jpg )'],
'SVG data URI with single quotes inside' => ['url("' . self::BOOTSTRAP_ARROW . '")'],
'SVG data URI with double quotes inside' => ["url('" . str_replace("'", '"', self::BOOTSTRAP_ARROW) . "')"],
'SVG data URI with a ;utf8 parameter' => ['url("' . str_replace('svg+xml,', 'svg+xml;utf8,', self::BOOTSTRAP_ARROW) . '")'],
];
}

}
62 changes: 62 additions & 0 deletions tests/Snapshots/StylesheetUrlSnapshotTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php

namespace Snapshots;

/**
* Background images named in a stylesheet's url() with spaces, whitespace inside the parentheses, or quotes inside
* the URL
*
* @group snapshot
*/
class StylesheetUrlSnapshotTest extends Snapshot
{

/**
* The fixture's name
*
* @return string
*/
public function getId()
{
return 'stylesheet-url';
}

/**
* Boxes with a background image each, under a caption saying what should be seen
*/
public function generatePdf()
{
$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";

$html = '<style>
body { font-size: 9pt; }
h1 { font-size: 15pt; margin: 0 0 2mm 0; }
p.caption { margin: 4mm 0 1mm 0; font-size: 8pt; color: #606060; }
div.box { width: 70mm; height: 20mm; border: 0.2mm solid #999999; background-repeat: no-repeat; }
div.spaced { background-image: url("img/bay eux.jpg"); }
div.padded { background-image: url( img/bay%20eux.jpg ); }
div.select { width: 60mm; height: 9mm; padding: 0 3mm; line-height: 9mm; background-image: url("' . $arrow . '"); background-position: right center; background-size: contain; }
div.double { background-image: url(\'' . str_replace("'", '"', $arrow) . '\'); background-size: contain; background-position: center; }
</style>

<h1>url() in a stylesheet</h1>

<p class="caption">url("img/bay eux.jpg"), with a space in the file name: the tapestry fills the box.</p>
<div class="box spaced"></div>

<p class="caption">url( img/bay%20eux.jpg ), with whitespace inside the parentheses: the same tapestry.</p>
<div class="box padded"></div>

<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>
<div class="box select">Choose</div>

<p class="caption">The same SVG with double quotes inside single quotes: a large chevron in the middle of the box.</p>
<div class="box double"></div>';

$this->mpdf = $this->createMpdf();
$this->mpdf->SetBasePath(__DIR__ . '/../data/');

$this->mpdf->WriteHTML($html);
}

}
Binary file added tests/data/snapshots/stylesheet-url.pdf
Binary file not shown.
Loading