Skip to content

Commit a56cfee

Browse files
jakejackson1claude
andcommitted
Read rgb() and hsl() written with spaces and a slash before the alpha
`color: rgb(255 0 0)` threw a TypeError out of WriteHTML(), because the colour converter split a function's arguments on commas only. The border, border-color, shadow and gradient parsers split the value on whitespace first, so there the colour was cut up and drawn wrong, with warnings. Split the arguments on commas, whitespace or a slash, read a fourth argument of rgb() or hsl() as the alpha, a percentage alpha as a fraction, and the hue as an angle in deg, grad, rad or turn. Write each rgb(), hsl() and cmyk() in a declaration with commas and no whitespace before the shorthand parsers see it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 2c9a90b commit a56cfee

8 files changed

Lines changed: 362 additions & 22 deletions

File tree

‎CHANGELOG-GRAVITYPDF.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,10 @@ Bugfixes
128128
* An inline `style` with `!important` drew no border for a `border` shorthand, dropped the bottom padding of a two-value `padding`, drew text at 0pt for a `font-size`, and ignored an image's `height` with a warning. The flag is now removed, as it is from a stylesheet. [mpdf/mpdf#1010] [mpdf/mpdf#1707] [#523] [#561]
129129
* Text styled with the `font` shorthand or `<font face>` came out as empty boxes when the family was not installed or had a space in its name, such as `font: 12pt Roboto` or `font: 16px "DejaVu Sans Mono"`. It was drawn in the first registered font, which is the emoji font in a full install. The family is now read as `font-family` reads it: a name is kept whole, the list is tried in order, and when mPDF knows none of it the text keeps the family it inherits. `font-family` itself also reads an unquoted name with spaces whole. [#552] [#560]
130130
* A descendant rule ending in `:lang()` or `[lang]`, such as `div :lang(fr)`, `div p:lang(fr)` or `table [lang=fr]`, never applied. It now applies in block content and in tables, and a regional language such as `fr-CA` falls back to the rule for `fr`, as the simple lang rules do. [#525] [#559]
131+
* `rgb()` and `hsl()` written with spaces, such as `color: rgb(255 0 0)`, threw a `TypeError` out of `WriteHTML()`, or drew the wrong colour with warnings. They are now read, with a slash before the alpha (`rgb(255 0 0 / 50%)`) and with the hue in `deg`, `grad`, `rad` or `turn`. [#552] [#563]
132+
* A percentage alpha, as in `rgba(255, 0, 0, 50%)`, gave an opacity above 1, which viewers draw opaque.
133+
* A fourth argument to `rgb()` or `hsl()` is read as the alpha instead of being dropped.
134+
* `border-color: rgb(255, 0, 0)` or `cmyk(0, 100, 0, 0)`, with spaces after the commas, drew black.
131135
* A percentage `width`, `min-width` or `max-width` on an image in a table cell was resolved against the block around the table, not the cell. In a 60mm cell, `max-width: 20%` came out as 36mm. [#223] [#505]
132136
* An `@page :left` or `@page :right` rule was ignored unless the style sheet also had a plain `@page` rule. With one, the margins of a `:right` rule were applied to left pages too. [#555] [#556]
133137
* When a later `WriteHTML()` call turned the document right to left, the text on the page already started was set between the swapped side margins. That page now keeps its margins, and the swap starts with the next page. [#554] [#558]
@@ -723,3 +727,4 @@ These changes do not change output.
723727
[#556]: https://github.com/GravityPDF/mpdf/pull/556
724728
[#558]: https://github.com/GravityPDF/mpdf/pull/558
725729
[#562]: https://github.com/GravityPDF/mpdf/pull/562
730+
[#563]: https://github.com/GravityPDF/mpdf/pull/563

‎src/Color/ColorConverter.php‎

Lines changed: 67 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,11 @@ class ColorConverter
1919

2020
const MODE_CMYKA = 6;
2121

22+
/**
23+
* What separates the arguments of a colour function: commas, whitespace, or the slash before an alpha
24+
*/
25+
const ARGUMENT_SEPARATOR = '/\s*[,\/]\s*|\s+/';
26+
2227
private $mpdf;
2328

2429
private $colorModeConverter;
@@ -275,11 +280,7 @@ private function convertPlain($color, array &$PDFAXwarnings = [])
275280
} elseif (strpos($color, '#') === 0) { // case of #nnnnnn or #nnn
276281
$c = $this->processHashColor($color);
277282
} elseif (preg_match('/(rgba|rgb|device-cmyka|cmyka|device-cmyk|cmyk|hsla|hsl|spot)\((.*?)\)/', $color, $m)) {
278-
// ignore colors containing CSS variables
279-
if (str_starts_with(mb_strtolower($m[2]), 'var(--')) {
280-
$m[2] = '0, 0, 0, 100';
281-
}
282-
$c = $this->processModeColor($m[1], explode(',', $m[2]));
283+
$c = $this->processModeColor($m[1], $this->splitArguments($m[1], $m[2]));
283284
}
284285

285286
if ($this->mpdf->PDFA || $this->mpdf->PDFX || $this->mpdf->restrictColorSpace) {
@@ -289,6 +290,30 @@ private function convertPlain($color, array &$PDFAXwarnings = [])
289290
return $c;
290291
}
291292

293+
/**
294+
* Splits the arguments of a colour function written with commas, rgb(255, 0, 0, 0.5), or with
295+
* spaces and a slash before the alpha, rgb(255 0 0 / 50%). A spot colour's name can contain
296+
* spaces, so only commas separate its arguments.
297+
*
298+
* @param string $mode The function name
299+
* @param string $arguments Everything between its parentheses
300+
*
301+
* @return string[]
302+
*/
303+
private function splitArguments($mode, $arguments)
304+
{
305+
// ignore colors containing CSS variables, and draw them black
306+
if (str_starts_with(mb_strtolower($arguments), 'var(--')) {
307+
return strpos($mode, 'cmyk') !== false ? ['0', '0', '0', '100'] : ['0', '0', '0'];
308+
}
309+
310+
if ($mode === 'spot') {
311+
return explode(',', $arguments);
312+
}
313+
314+
return preg_split(static::ARGUMENT_SEPARATOR, trim($arguments));
315+
}
316+
292317
/**
293318
* @param string $color
294319
*
@@ -323,11 +348,19 @@ private function processModeColor($mode, array $cores)
323348
$cores = $this->convertPercentCoreValues($mode, $cores);
324349

325350
switch ($mode) {
326-
case 'rgb':
327-
return [static::MODE_RGB, $cores[0], $cores[1], $cores[2]];
351+
// rgb() and rgba() are the same function, as are hsl() and hsla(): a fourth argument is the alpha
352+
case 'hsl':
353+
case 'hsla':
354+
list($cores[0], $cores[1], $cores[2]) = $this->colorModeConverter->hsl2rgb($this->hueTurns($cores[0]), $cores[1], $cores[2]);
355+
// no break
328356

357+
case 'rgb':
329358
case 'rgba':
330-
return [static::MODE_RGBA, $cores[0], $cores[1], $cores[2], $cores[3] * 100];
359+
if (isset($cores[3])) {
360+
return [static::MODE_RGBA, $cores[0], $cores[1], $cores[2], $cores[3] * 100];
361+
}
362+
363+
return [static::MODE_RGB, $cores[0], $cores[1], $cores[2]];
331364

332365
case 'cmyk':
333366
case 'device-cmyk':
@@ -337,14 +370,6 @@ private function processModeColor($mode, array $cores)
337370
case 'device-cmyka':
338371
return [static::MODE_CMYKA, $cores[0], $cores[1], $cores[2], $cores[3], $cores[4] * 100];
339372

340-
case 'hsl':
341-
$conv = $this->colorModeConverter->hsl2rgb($cores[0] / 360, $cores[1], $cores[2]);
342-
return [static::MODE_RGB, $conv[0], $conv[1], $conv[2]];
343-
344-
case 'hsla':
345-
$conv = $this->colorModeConverter->hsl2rgb($cores[0] / 360, $cores[1], $cores[2]);
346-
return [static::MODE_RGBA, $conv[0], $conv[1], $conv[2], $cores[3] * 100];
347-
348373
case 'spot':
349374
$name = strtoupper(trim($cores[0]));
350375

@@ -371,41 +396,62 @@ private function processModeColor($mode, array $cores)
371396
private function convertPercentCoreValues($mode, array $cores)
372397
{
373398
$ncores = count($cores);
399+
$isRgb = $mode === 'rgb' || $mode === 'rgba';
400+
$isHsl = $mode === 'hsl' || $mode === 'hsla';
374401

375402
if (strpos($cores[0], '%') !== false) {
376403
$cores[0] = (float) $cores[0];
377-
if ($mode === 'rgb' || $mode === 'rgba') {
404+
if ($isRgb) {
378405
$cores[0] = (int) ($cores[0] * 255 / 100);
379406
}
380407
}
381408

382409
if ($ncores > 1 && strpos($cores[1], '%') !== false) {
383410
$cores[1] = (float) $cores[1];
384-
if ($mode === 'rgb' || $mode === 'rgba') {
411+
if ($isRgb) {
385412
$cores[1] = (int) ($cores[1] * 255 / 100);
386413
}
387-
if ($mode === 'hsl' || $mode === 'hsla') {
414+
if ($isHsl) {
388415
$cores[1] /= 100;
389416
}
390417
}
391418

392419
if ($ncores > 2 && strpos($cores[2], '%') !== false) {
393420
$cores[2] = (float) $cores[2];
394-
if ($mode === 'rgb' || $mode === 'rgba') {
421+
if ($isRgb) {
395422
$cores[2] = (int) ($cores[2] * 255 / 100);
396423
}
397-
if ($mode === 'hsl' || $mode === 'hsla') {
424+
if ($isHsl) {
398425
$cores[2] /= 100;
399426
}
400427
}
401428

402429
if ($ncores > 3 && strpos($cores[3], '%') !== false) {
403430
$cores[3] = (float) $cores[3];
431+
// the fourth argument of rgb() and hsl() is the alpha, a fraction; of cmyk() it is the black, a percentage
432+
if ($isRgb || $isHsl) {
433+
$cores[3] /= 100;
434+
}
404435
}
405436

406437
return $cores;
407438
}
408439

440+
/**
441+
* @param string|float $hue A number of degrees, or an angle in deg, grad, rad or turn
442+
*
443+
* @return float The hue as a fraction of a full turn, from 0 up to 1
444+
*/
445+
private function hueTurns($hue)
446+
{
447+
$perTurn = ['deg' => 360, 'grad' => 400, 'rad' => 2 * M_PI, 'turn' => 1];
448+
449+
preg_match('/[a-z]*$/', (string) $hue, $unit);
450+
$turns = fmod((float) $hue / (isset($perTurn[$unit[0]]) ? $perTurn[$unit[0]] : 360), 1);
451+
452+
return $turns < 0 ? $turns + 1 : $turns;
453+
}
454+
409455
/**
410456
* @param mixed $c
411457
* @param string $color

‎src/Css/NormalizeProperties.php‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,8 @@ public function normalize($prop)
6464
$v = strtolower($v);
6565
}
6666

67+
$v = $this->compactColorFunctions($v);
68+
6769
if ($k === 'FONT') {
6870
$this->processFontProperty($v);
6971
} elseif ($k === 'FONT-FAMILY') {
@@ -114,6 +116,26 @@ public function normalize($prop)
114116
return $this->properties;
115117
}
116118

119+
/**
120+
* Writes the arguments of each rgb(), hsl() and cmyk() with commas and no whitespace, so the parsers
121+
* that split a value on whitespace (border, border-color, shadows, gradients) keep the colour whole:
122+
* rgb(255 0 0 / 50%) becomes rgb(255,0,0,50%). A spot colour's name can contain spaces, so spot()
123+
* is left alone.
124+
*
125+
* @param string $value Property value
126+
* @return string
127+
*/
128+
private function compactColorFunctions($value)
129+
{
130+
if (stripos($value, 'rgb') === false && stripos($value, 'hsl') === false && stripos($value, 'cmyk') === false) {
131+
return $value;
132+
}
133+
134+
return preg_replace_callback('/\b(rgba?|hsla?|(?:device-)?cmyka?)\(([^()]*)\)/i', static function ($m) {
135+
return $m[1] . '(' . preg_replace(ColorConverter::ARGUMENT_SEPARATOR, ',', trim($m[2])) . ')';
136+
}, $value);
137+
}
138+
117139
/**
118140
* Process FONT shorthand property.
119141
*

‎tests/Mpdf/Color/ColorConverterTest.php‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,60 @@ public function convertColorsProvider()
9696
];
9797
}
9898

99+
/**
100+
* rgb(), rgba(), hsl() and hsla() written with spaces and a slash before the alpha, with a fourth comma-separated
101+
* argument as the alpha, with a percentage alpha, and with the hue as an angle
102+
*
103+
* @dataProvider modernSyntaxProvider
104+
*
105+
* @param string $input
106+
* @param string $output
107+
*/
108+
public function testConvertModernSyntax($input, $output)
109+
{
110+
$converter = new ColorConverter($this->mpdf, new ColorModeConverter(), $this->restrictor);
111+
112+
$this->assertSame($output, $converter->convert($input));
113+
}
114+
115+
/**
116+
* Each colour, and its binary string: the mode, then the channels, then the alpha as a percentage
117+
*
118+
* @return string[][]
119+
*/
120+
public function modernSyntaxProvider()
121+
{
122+
return [
123+
['rgb(255 0 0)', "3\xff\x00\x00\x00\x00"],
124+
['rgb( 255 128 0 )', "3\xff\x80\x00\x00\x00"],
125+
['rgb(100% 0% 50%)', "3\xff\x00\x7f\x00\x00"],
126+
['rgb(255 0 0 / 50%)', "5\xff\x00\x002\x00"],
127+
['rgb(255 0 0/.25)', "5\xff\x00\x00\x19\x00"],
128+
['rgba(255 0 0 / 0.5)', "5\xff\x00\x002\x00"],
129+
['rgba(255 0 0)', "3\xff\x00\x00\x00\x00"],
130+
['rgb(255, 0, 0, 0.5)', "5\xff\x00\x002\x00"],
131+
['rgba(255, 0, 0, 50%)', "5\xff\x00\x002\x00"],
132+
133+
['hsl(120 100% 50%)', "3\x00\xff\x00\x00\x00"],
134+
['hsl(120 100% 50% / .5)', "5\x00\xff\x002\x00"],
135+
['hsla(120 100% 50% / 50%)', "5\x00\xff\x002\x00"],
136+
['hsl(120, 100%, 50%, 0.5)', "5\x00\xff\x002\x00"],
137+
['hsla(120, 100%, 50%)', "3\x00\xff\x00\x00\x00"],
138+
139+
['hsl(120deg 100% 50%)', "3\x00\xff\x00\x00\x00"],
140+
['hsl(120deg, 100%, 50%)', "3\x00\xff\x00\x00\x00"],
141+
['hsl(0.5turn 100% 50%)', "3\x00\xff\xff\x00\x00"],
142+
['hsl(200grad 100% 50%)', "3\x00\xff\xff\x00\x00"],
143+
['hsl(3.14159265rad 100% 50%)', "3\x00\xff\xff\x00\x00"],
144+
['hsl(-120 100% 50%)', "3\x00\x00\xff\x00\x00"],
145+
['hsl(480 100% 50%)', "3\x00\xff\x00\x00\x00"],
146+
147+
['rgb(var(--red))', "3\x00\x00\x00\x00\x00"],
148+
['rgba(var(--red))', "3\x00\x00\x00\x00\x00"],
149+
['cmyk(var(--black))', "4\x00\x00\x00d\x00"],
150+
];
151+
}
152+
99153
public function testConvertUnknownSpotColor()
100154
{
101155
$this->expectException(\Mpdf\MpdfException::class);
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
<?php
2+
3+
namespace Mpdf;
4+
5+
/**
6+
* rgb() and hsl() written with spaces, and with a slash before the alpha, in every property that takes a colour. Each
7+
* case must draw what the same colour written with commas draws, without a warning.
8+
*/
9+
class ModernColorSyntaxTest extends \Yoast\PHPUnitPolyfills\TestCases\TestCase
10+
{
11+
12+
use PageStreams;
13+
14+
/**
15+
* @dataProvider colorsProvider
16+
*
17+
* @param string $modern HTML using the space-separated syntax
18+
* @param string $legacy The same HTML using commas
19+
* @param string $drawn An operator, or an opacity, the document must contain
20+
*/
21+
public function testDrawsAsTheCommaSyntaxDoes($modern, $legacy, $drawn)
22+
{
23+
$expected = $this->drawn($legacy);
24+
$actual = $this->drawn($modern);
25+
26+
$this->assertSame($expected, $actual);
27+
$this->assertStringContainsString($drawn, implode("\n", $actual['pages']) . "\n" . implode("\n", $actual['opacities']));
28+
}
29+
30+
/**
31+
* Each case: the space-separated syntax, the comma-separated one, and something only the right colour draws
32+
*
33+
* @return string[][]
34+
*/
35+
public function colorsProvider()
36+
{
37+
$block = '<div style="%s">Text</div>';
38+
$sheet = '<style>div.c { %s }</style><div class="c">Text</div>';
39+
40+
$cases = [
41+
'color in a stylesheet' => [$sheet, 'color: rgb(255 0 0)', 'color: rgb(255,0,0)', '1.000 0.000 0.000 rg'],
42+
'color in a style attribute' => [$block, 'color: rgb(255 0 0)', 'color: rgb(255,0,0)', '1.000 0.000 0.000 rg'],
43+
'background-color with a slash alpha' => [$sheet, 'background-color: rgb(255 0 0 / 50%)', 'background-color: rgba(255,0,0,0.5)', '/ca 0.5'],
44+
'background with hsl and a slash alpha' => [$sheet, 'background: hsl(120 100% 25% / .5)', 'background: hsla(120,100%,25%,0.5)', '/ca 0.5'],
45+
'border' => [$sheet, 'border: 1mm solid rgb(255 0 0)', 'border: 1mm solid rgb(255,0,0)', '1.000 0.000 0.000 RG'],
46+
'border-color with two colours' => [
47+
$sheet,
48+
'border: 1mm solid; border-color: rgb(255 0 0) hsl(240 100% 50%)',
49+
'border: 1mm solid; border-color: rgb(255,0,0) hsl(240,100%,50%)',
50+
'0.000 0.000 1.000 RG',
51+
],
52+
'border-color with spaces after the commas' => [
53+
$sheet,
54+
'border: 1mm solid; border-color: rgb(255, 0, 0)',
55+
'border: 1mm solid; border-color: rgb(255,0,0)',
56+
'1.000 0.000 0.000 RG',
57+
],
58+
'border-color with cmyk() and spaces after the commas' => [
59+
$sheet,
60+
'border: 1mm solid; border-color: cmyk(0, 100, 0, 0)',
61+
'border: 1mm solid; border-color: cmyk(0,100,0,0)',
62+
'0.000 1.000 0.000 0.000 K',
63+
],
64+
'box-shadow' => [$sheet, 'box-shadow: 1mm 1mm rgb(255 0 0 / .5)', 'box-shadow: 1mm 1mm rgba(255,0,0,0.5)', '/ca 0.5'],
65+
'text-shadow' => [$sheet, 'text-shadow: 1mm 1mm rgb(0 0 255)', 'text-shadow: 1mm 1mm rgb(0,0,255)', '0.000 0.000 1.000 rg'],
66+
'linear-gradient' => [
67+
$sheet,
68+
'height: 10mm; background: linear-gradient(to right, rgb(255 0 0) 10%, hsl(240 100% 50%) 90%)',
69+
'height: 10mm; background: linear-gradient(to right, rgb(255,0,0) 10%, hsl(240,100%,50%) 90%)',
70+
'/Sh',
71+
],
72+
'hsl() with deg' => [$sheet, 'color: hsl(240deg 100% 50%)', 'color: hsl(240,100%,50%)', '0.000 0.000 1.000 rg'],
73+
'hsl() with turn' => [$sheet, 'color: hsl(0.5turn 100% 50%)', 'color: hsl(180,100%,50%)', '0.000 1.000 1.000 rg'],
74+
'hsl() with rad' => [$sheet, 'color: hsl(3.14159265rad 100% 50%)', 'color: hsl(180,100%,50%)', '0.000 1.000 1.000 rg'],
75+
];
76+
77+
$data = [];
78+
foreach ($cases as $name => $case) {
79+
$data[$name] = [sprintf($case[0], $case[1]), sprintf($case[0], $case[2]), $case[3]];
80+
}
81+
82+
$data['bgcolor attribute'] = [
83+
'<table><tr><td bgcolor="rgb(0 0 255)">Text</td></tr></table>',
84+
'<table><tr><td bgcolor="rgb(0,0,255)">Text</td></tr></table>',
85+
'0.000 0.000 1.000 rg',
86+
];
87+
88+
return $data;
89+
}
90+
91+
/**
92+
* What a document draws: its page content streams, and the fill and stroke opacities of its graphics states.
93+
* Asserts that drawing it raised no warning.
94+
*
95+
* @param string $html
96+
*
97+
* @return string[][]
98+
*/
99+
private function drawn($html)
100+
{
101+
$pdf = $this->assertDrawsSilently(function (Mpdf $mpdf) use ($html) {
102+
$mpdf->WriteHTML($html);
103+
});
104+
105+
preg_match_all('#/(?:ca|CA) [\d.]+#', $pdf, $opacities);
106+
107+
return ['pages' => $this->pages($pdf), 'opacities' => $opacities[0]];
108+
}
109+
110+
}

0 commit comments

Comments
 (0)