Skip to content

Commit

Permalink
esc() for 'raw' context (Fixes #8624)
Browse files Browse the repository at this point in the history
  • Loading branch information
Cleric-K committed Mar 20, 2024
1 parent b8adef6 commit 0b930cc
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 12 deletions.
18 changes: 9 additions & 9 deletions system/Common.php
Original file line number Diff line number Diff line change
Expand Up @@ -426,22 +426,22 @@ function env(string $key, $default = null)
*/
function esc($data, string $context = 'html', ?string $encoding = null)
{
$context = strtolower($context);

// Provide a way to NOT escape data since
// this could be called automatically by
// the View library.
if ($context === 'raw') {
return $data;
}

if (is_array($data)) {
foreach ($data as &$value) {
$value = esc($value, $context);
}
}

if (is_string($data)) {
$context = strtolower($context);

// Provide a way to NOT escape data since
// this could be called automatically by
// the View library.
if ($context === 'raw') {
return $data;
}

if (! in_array($context, ['html', 'js', 'css', 'url', 'attr'], true)) {
throw new InvalidArgumentException('Invalid escape context provided.');
}
Expand Down
18 changes: 15 additions & 3 deletions system/ThirdParty/Escaper/Escaper.php
Original file line number Diff line number Diff line change
Expand Up @@ -157,9 +157,21 @@ public function __construct(?string $encoding = null)
$this->htmlSpecialCharsFlags = ENT_QUOTES | ENT_SUBSTITUTE;

// set matcher callbacks
$this->htmlAttrMatcher = [$this, 'htmlAttrMatcher'];
$this->jsMatcher = [$this, 'jsMatcher'];
$this->cssMatcher = [$this, 'cssMatcher'];
$this->htmlAttrMatcher =
/** @param array<array-key, string> $matches */
function (array $matches): string {
return $this->htmlAttrMatcher($matches);
};
$this->jsMatcher =
/** @param array<array-key, string> $matches */
function (array $matches): string {
return $this->jsMatcher($matches);
};
$this->cssMatcher =
/** @param array<array-key, string> $matches */
function (array $matches): string {
return $this->cssMatcher($matches);
};
}

/**
Expand Down
21 changes: 21 additions & 0 deletions tests/system/CommonFunctionsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,27 @@ public function testEscapeBadContextZero(): void
esc('<script>', '0');
}

public function testEscapeArray(): void
{
$data = [
'a' => [
'b' => 'c&',
],
'd' => 'e>',
];
$expected = $data;
$expected['a']['b'] = 'c&amp;';
$expected['d'] = 'e&gt;';
$this->assertSame($expected, esc($data));
}

public function testEscapeRecursiveArrayRaw(): void
{
$data = ['a' => 'b', 'c' => 'd'];
$data['e'] = &$data;
$this->assertSame($data, esc($data, 'raw'));
}

/**
* @runInSeparateProcess
* @preserveGlobalState disabled
Expand Down

0 comments on commit 0b930cc

Please sign in to comment.