Skip to content

Commit

Permalink
fix: apply suggested replsce solution
Browse files Browse the repository at this point in the history
  • Loading branch information
kilatib committed Nov 6, 2024
1 parent c2114fd commit 99af487
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 22 deletions.
78 changes: 57 additions & 21 deletions src/qtism/data/storage/xml/Utils.php
Original file line number Diff line number Diff line change
Expand Up @@ -360,29 +360,65 @@ public static function valueAsString($value, $encode = true): string
return (string)$value;
}

public static function escapeNonCharacterRange(string $string): string
private static function isInCharacterRange(int $char): bool
{
// Define the XML escape sequences
$symbolMap = [
'"' => '"',
"'" => ''',
'&' => '&',
'<' => '&lt;',
'>' => '&gt;',
"\t" => '&#x9;',
"\r" => '&#xD;',
"\x08" => '&#xFFFD;',
];

for ($char = 0xE000; $char <= 0xFFFD; $char++) {
$symbolMap[mb_chr($char, 'UTF-8')] = '\u{FFFD}';
}
for ($char = 0x10000; $char <= 0x10FFFF; $char++) {
$symbolMap[mb_chr($char, 'UTF-8')] = '\u{FFFD}';
}
$string = strtr($string, $symbolMap);
return $char == 0x09
|| $char == 0x0A
|| $char == 0x0D
|| $char >= 0x20 && $char <= 0xDF77
|| $char >= 0xE000 && $char <= 0xFFFD
|| $char >= 0x10000 && $char <= 0x10FFFF;
}

return htmlspecialchars($string, ENT_QUOTES | ENT_XML1, 'UTF-8');
public static function escapeNonCharacterRange(string $value): string
{
$result = '';

$last = 0;
$length = strlen($value);
$i = 0;

while ($i < $length) {
$r = mb_substr(substr($value, $i), 0, 1);
$width = strlen($r);
$i += $width;
switch ($r) {
case '"':
$esc = '&#34;';
break;
case "'":
$esc = '&#39;';
break;
case '&':
$esc = '&amp;';
break;
case '<':
$esc = '&lt;';
break;
case '>':
$esc = '&gt;';
break;
case "\t":
$esc = '&#x9;';
break;
case "\n":
$esc = '&#xA;';
break;
case "\r":
$esc = '&#xD;';
break;
default:
if (!self::isInCharacterRange(mb_ord($r)) || (mb_ord($r) === 0xFFFD && $width === 1)) {
$esc = "\u{FFFD}";
break;
}

continue 2;
}
$result .= substr($value, $last, $i - $last - $width) . $esc;
$last = $i;
}
return $result . substr($value, $last);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion test/qtismtest/data/storage/xml/XmlUtilsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,7 @@ public function testFindCustomNamespaces(): void
public function testValueAsStringReplaceSpecialSymbols(): void
{
$xml = ('<value>160°</value>');
$this->assertEquals('&amp;lt;value&amp;gt;160°&amp;#xFFFD;&amp;lt;/value&amp;gt;', Utils::valueAsString($xml));
$this->assertEquals('&lt;value&gt;160°�&lt;/value&gt;', Utils::valueAsString($xml));
}

public function testProcessSpecialCharsetWithoutError(): void
Expand Down

0 comments on commit 99af487

Please sign in to comment.