| File: | blib/lib/Encode/Wide.pm |
| Coverage: | 100.0% |
| line | stmt | bran | cond | sub | time | code |
|---|---|---|---|---|---|---|
| 1 | package Encode::Wide; | |||||
| 2 | ||||||
| 3 | # TODO: don't transform anything within <script>...</script> in wide_to_html | |||||
| 4 | ||||||
| 5 | 10 10 10 | 919308 8 86 | use strict; | |||
| 6 | 10 10 10 | 14 7 203 | use warnings; | |||
| 7 | ||||||
| 8 | 10 10 10 | 15 6 248 | use Carp qw(croak carp confess); | |||
| 9 | 10 10 10 | 14 7 106 | use Exporter qw(import); | |||
| 10 | 10 10 10 | 1333 21367 464 | use HTML::Entities; | |||
| 11 | 10 10 10 | 1035 101677 10707 | use Params::Get 0.13; | |||
| 12 | ||||||
| 13 | our @EXPORT_OK = qw(wide_to_html wide_to_xml); | |||||
| 14 | ||||||
| 15 | # HTML::Entities::decode does not handle these four named entities, so we | |||||
| 16 | # decode them ourselves. The regex is built once at compile time: longest | |||||
| 17 | # key first to avoid partial-match ambiguity (e.g. Š before &s...). | |||||
| 18 | my %_EXTRA_ENTITY_MAP = ( | |||||
| 19 | 'č' => "\x{010D}", # c with caron | |||||
| 20 | 'ž' => "\x{017E}", # z with caron | |||||
| 21 | 'Ž' => "\x{017D}", # Z with caron | |||||
| 22 | 'Š' => "\x{0160}", # S with caron | |||||
| 23 | ); | |||||
| 24 | my $_EXTRA_ENTITY_RE = do { | |||||
| 25 | my $pat = join '|', map { quotemeta } | |||||
| 26 | sort { length($b) <=> length($a) } keys %_EXTRA_ENTITY_MAP; | |||||
| 27 | qr/$pat/; | |||||
| 28 | }; | |||||
| 29 | ||||||
| 30 | # Module-level HTML escape map eliminates the /e eval flag in keep_hrefs substitutions | |||||
| 31 | my %_HTML_ESCAPE = ( '<' => '<', '>' => '>', '"' => '"' ); | |||||
| 32 | ||||||
| 33 | # Encode to HTML whatever the non-ASCII encoding scheme has been chosen | |||||
| 34 | # Can't use HTML:Entities::encode since that doesn't seem to cope with | |||||
| 35 | # all encodings and misses some characters | |||||
| 36 | # | |||||
| 37 | # See https://www.compart.com/en/unicode/U+0161 etc. | |||||
| 38 | # https://www.compart.com/en/unicode/U+00EB | |||||
| 39 | # | |||||
| 40 | # keep_hrefs => 1 means ensure hyperlinks still work | |||||
| 41 | # keep_apos => 1 means keep apostrophes, useful within <script> | |||||
| 42 | ||||||
| 43 - 51 | =head1 NAME Encode::Wide - Convert wide characters (Unicode, UTF-8, etc.) into ASCII-safe HTML or XML entities =head1 VERSION 0.07 =cut | |||||
| 52 | ||||||
| 53 | our $VERSION = 0.07; | |||||
| 54 | ||||||
| 55 | =encoding UTF-8 | |||||
| 56 | ||||||
| 57 - 341 | =head1 SYNOPSIS
use Encode::Wide qw(wide_to_html wide_to_xml);
# Basic HTML conversion
my $html = wide_to_html(string => "Cafe\x{E9} d\x{E9}j\x{E0} vu");
# => 'Café déjà vu'
# Basic XML conversion (numeric entities, en-dash folded to hyphen)
my $xml = wide_to_xml(string => "Cafe\x{E9} \x{2013} na\x{EF}ve");
# => 'Café - naïve'
# Preserve embedded HTML markup (keep_hrefs)
my $linked = wide_to_html(
string => '<a href="/menu">Caf\x{E9}</a>',
keep_hrefs => 1,
);
# => '<a href="/menu">Café</a>'
# Keep apostrophes literal for JavaScript contexts (keep_apos)
my $js_safe = wide_to_html(
string => "it\x{2019}s na\x{EF}ve",
keep_apos => 1,
);
# => "it\x{2019}s naïve" (curly apostrophe kept; i-umlaut encoded)
# Get notified about unhandled characters instead of dying silently
my $out = wide_to_html(
string => $untrusted,
complain => sub { warn "Unhandled: $_[0]" },
);
# Accept a scalar reference
my $text = "na\x{EF}ve";
my $safe = wide_to_html(string => \$text);
# => 'naïve'
=head1 DESCRIPTION
Encode::Wide converts strings that contain non-ASCII (wide) characters into
pure 7-bit ASCII output suitable for embedding in HTML pages or XML documents.
Every non-ASCII codepoint is replaced by the appropriate entity reference so
the output can be safely placed in HTML attributes, HTML body text, or XML
element content without triggering encoding errors or security issues.
=head2 Why use this module?
L<HTML::Entities> is the obvious alternative for HTML, but it makes strict
assumptions about input encoding that cause silent failures when the input
arrives as raw UTF-8 bytes, already-partially-encoded entities, or a mix of
both. Encode::Wide handles all three representations through a multi-pass
pipeline and falls back to L<HTML::Entities> numeric encoding for any
character not explicitly listed in its tables.
For XML, L<XML::Entities> works in the opposite direction (decoding entities,
not encoding them). Encode::Wide fills that gap.
=head2 Input
Both functions accept:
=over 4
=item *
A B<Perl Unicode string> (the internal C<utf8> flag is set) - the normal case
when input comes from L<Encode/decode>, a database driver with C<pg_enable_utf8>,
or a source file declared C<use utf8>.
=item *
A B<raw UTF-8 byte string> - the common case when input arrives from a legacy
web form or an older database driver without automatic decoding. The pipeline's
raw-byte substitution pass handles this transparently.
=item *
A B<scalar reference> - C<wide_to_html(string =E<gt> \$var)>. The string is
read from the referent; the referent is not modified.
=item *
B<Already-encoded HTML entities> - e.g. C<é> or C<<>.
By default the pipeline decodes these first so they are not double-encoded.
Pass C<keep_hrefs =E<gt> 1> to suppress decoding when the input contains
trusted HTML that must pass through unchanged.
=back
=head2 Output
Both functions return a B<defined scalar string> containing B<only ASCII
characters> (code points 0x00-0x7F). The output is safe to concatenate
directly into an HTML or XML document without further escaping.
=head2 Choosing between the two functions
Use C<wide_to_html> when writing into an HTML context (C<< <p> >>, C<< <td> >>,
attribute values, etc.). Named entities such as C<é> and C<–>
are used wherever possible; they are compact and human-readable in the source.
Use C<wide_to_xml> when writing into an XML context (XHTML, RSS, Atom, custom
XML schemas). Named HTML entities other than the five predefined XML entities
(C<&> C<<> C<>> C<'> C<">) are not valid in XML.
This function uses only hexadecimal numeric entities (C<é>), which are
valid in all XML 1.0 processors. Em-dashes and en-dashes are folded to a
plain ASCII hyphen because many XML consumers normalise whitespace and
punctuation anyway.
=head1 EXPORT
Nothing is exported by default. Import the functions you need explicitly:
use Encode::Wide qw(wide_to_html); # one function
use Encode::Wide qw(wide_to_html wide_to_xml); # both
=head1 COMMON PARAMETERS
Both functions accept the following named parameters in addition to C<string>.
Pass them as a flat key-value list:
wide_to_html(string => $text, keep_hrefs => 1, complain => \&handler);
=over 4
=item C<string> (required)
The text to encode. May be a plain scalar or a B<reference to a scalar>.
Must be defined; passing C<undef> causes the function to C<croak> with a
usage message.
=item C<keep_hrefs> (optional, default 0)
When true, angle brackets (C<< < >>, C<< > >>) and double-quotes (C<">) are
B<not> escaped, allowing embedded HTML or XML markup to survive intact.
B<Security note:> when C<keep_hrefs> is set, entity-decoding is also
suppressed. Without this suppression, an encoded payload such as
C<<script>> would be decoded to C<< <script> >> and then pass through
unescaped, creating an XSS vector. With C<keep_hrefs =E<gt> 1> it is the
B<caller's responsibility> to ensure that the input does not contain untrusted
content that could be exploited.
=item C<complain> (optional)
A code reference called with a diagnostic string when the pipeline encounters a
character it cannot encode. The function still C<croak>s with a C<BUG:>
prefix after invoking the callback - C<complain> is for logging, not recovery.
wide_to_html(
string => $text,
complain => sub {
my ($msg) = @_;
warn "Encode::Wide gap: $msg";
},
);
=back
=head2 wide_to_html
Convert a Unicode or UTF-8 string into a pure-ASCII HTML fragment. Every
non-ASCII character is replaced by its named HTML entity (e.g. C<é>)
where one exists, or a hexadecimal numeric entity (e.g. C<&#xNNNN;>) otherwise.
Bare ampersands, angle brackets, and double-quotes are also escaped so the
result is safe to embed in HTML body text or attribute values without further
processing.
=head3 Arguments
All parameters are passed as a flat key-value list. The C<string> key may be
omitted when passing a bare positional string as the first argument.
See L</COMMON PARAMETERS> for C<string>, C<keep_hrefs>, and C<complain>.
=over 4
=item C<keep_apos> (optional, default 0)
When true, apostrophes and their typographic variants (curly single quotes
U+2018, U+2019; grave accent U+0060; Windows-1252 byte 0x98) are B<not>
converted to C<'>. Useful when the result will be embedded inside a
JavaScript string literal where C<'> is not valid syntax.
=back
=head3 Returns
A defined scalar string whose every character is in the ASCII range
(code points 0x00-0x7F). The empty string is returned unchanged.
=head3 EXAMPLE
use Encode::Wide qw(wide_to_html);
# Accented characters to named entities
my $out = wide_to_html(string => "na\x{EF}ve caf\x{E9}");
# => 'naïve café'
# Ampersands and angle brackets are escaped
$out = wide_to_html(string => 'Price < 100 & cost > 0');
# => 'Price < 100 & cost > 0'
# Existing entities are decoded then re-encoded (no double-encoding)
$out = wide_to_html(string => 'é');
# => 'é'
# keep_hrefs: HTML markup passes through; only wide chars are encoded
$out = wide_to_html(
string => '<a href="/m\x{E9}nu">Men\x{FC}</a>',
keep_hrefs => 1,
);
# => '<a href="/ménu">Menü</a>'
# keep_apos: apostrophes kept for JavaScript contexts
$out = wide_to_html(
string => "it\x{2019}s clich\x{E9}",
keep_apos => 1,
);
# => "it\x{2019}s cliché"
# Scalar reference input
my $text = "caf\x{E9}";
$out = wide_to_html(string => \$text);
# => 'café'
=head3 MESSAGES
=over 4
=item C<Usage: wide_to_html() string not set>
B<Fatal> (via C<croak>). The C<string> parameter was C<undef>.
Resolution: pass a defined scalar or scalar reference.
=item C<TODO: wide_to_html(E<lt>hex-tokens...E<gt>)>
B<Warning> (via C<carp>). A character survived all three byte_map passes and
the C<encode_entities_numeric> fallback. The hex tokens in the message
identify the unhandled codepoint(s).
Resolution: add the character to the appropriate byte_map array, or file a bug
report at L<https://rt.cpan.org/Public/Dist/Display.html?Name=Encode-Wide>.
=item C<BUG: wide_to_html(E<lt>hex-tokens...E<gt>)>
B<Fatal> (via C<croak>), always preceded by the C<TODO> warning above.
The same unhandled-character condition caused a hard failure. This should
never occur in normal use; it indicates a gap in the character tables.
=back
=head3 API SPECIFICATION
=head4 Input
{
string => { type => SCALAR | SCALARREF, required => 1, defined => 1 },
keep_hrefs => { type => BOOLEAN, optional => 1, default => 0 },
keep_apos => { type => BOOLEAN, optional => 1, default => 0 },
complain => { type => CODEREF, optional => 1 },
}
=head4 Output
{ type => SCALAR, constraint => sub { $_[0] !~ /[^[:ascii:]]/ } }
=head3 PSEUDOCODE
1. Unless keep_hrefs: decode HTML entities via HTML::Entities::decode
and the four extra named entities (č ž Ž Š)
2. Escape bare & not followed by a valid entity name
(possessive ++ quantifier prevents ReDoS backtracking)
3. Unless keep_hrefs: escape <, >, and " using %_HTML_ESCAPE (no /e eval)
4. First byte_map pass: typographic punctuation and exclamation mark
5. Unless keep_apos: encode apostrophe variants to '
using an alternation regex built from the apostrophe key set
6. Early return if the string is now pure ASCII
7. Second byte_map pass: raw UTF-8 byte sequences -> named HTML entities
8. Third byte_map pass: Perl Unicode chars (\N{U+...}) -> named HTML entities
9. Fallback: HTML::Entities::encode_entities_numeric for any remaining
non-ASCII codepoints
10. If non-ASCII still remains after the fallback: invoke complain callback,
carp a TODO warning, then croak a BUG error
=cut | |||||
| 342 | ||||||
| 343 | sub wide_to_html | |||||
| 344 | { | |||||
| 345 | 295 | 491779 | my $params = Params::Get::get_params('string', @_); | |||
| 346 | ||||||
| 347 | 293 | 3199 | my $string = $params->{'string'}; | |||
| 348 | 293 | 180 | my $complain = $params->{'complain'}; | |||
| 349 | ||||||
| 350 | 293 | 255 | if(!defined($string)) { | |||
| 351 | 4 | 49 | croak 'Usage: wide_to_html() string not set'; | |||
| 352 | } | |||||
| 353 | ||||||
| 354 | 289 | 346 | if(ref($string) eq 'SCALAR') { | |||
| 355 | 21 21 | 8 19 | $string = ${$string}; | |||
| 356 | } | |||||
| 357 | ||||||
| 358 | ||||||
| 359 | # SECURITY: skip entity-decoding when keep_hrefs is set. Calling | |||||
| 360 | # HTML::Entities::decode before the keep_hrefs gate converts encoded | |||||
| 361 | # payloads like <script> to raw <script>, which then bypass | |||||
| 362 | # re-escaping and produce XSS output. When the caller asserts the input | |||||
| 363 | # contains trusted HTML (keep_hrefs => 1) we treat the text as-is and | |||||
| 364 | # only encode wide characters; entity-normalisation is then the caller's | |||||
| 365 | # responsibility. | |||||
| 366 | 289 | 256 | unless($params->{'keep_hrefs'}) { | |||
| 367 | 271 | 481 | $string = HTML::Entities::decode($string); | |||
| 368 | ||||||
| 369 | # Decode the four named entities HTML::Entities::decode misses | |||||
| 370 | 271 | 692 | $string =~ s/($_EXTRA_ENTITY_RE)/$_EXTRA_ENTITY_MAP{$1}/g; | |||
| 371 | } | |||||
| 372 | ||||||
| 373 | # Escape bare & not already part of a valid entity. | |||||
| 374 | # Possessive ++ on the char class prevents O(n^2) backtracking (ReDoS) | |||||
| 375 | # when the input contains & not followed by a semicolon-terminated name. | |||||
| 376 | 289 | 264 | $string =~ s/&(?![A-Za-z#0-9]++;)/&/g; | |||
| 377 | ||||||
| 378 | 289 | 209 | unless($params->{'keep_hrefs'}) { | |||
| 379 | # Escape the three characters that break HTML attribute or body contexts. | |||||
| 380 | # Module-level %_HTML_ESCAPE eliminates the /e eval flag. | |||||
| 381 | 271 | 340 | $string =~ s/([<>"])/$_HTML_ESCAPE{$1}/g; | |||
| 382 | } | |||||
| 383 | ||||||
| 384 | # $string =~ s/&db=/&db=/g; | |||||
| 385 | # $string =~ s/&id=/&id=/g; | |||||
| 386 | ||||||
| 387 | # Table of byte-sequences->entities | |||||
| 388 | 289 | 642 | my @byte_map = ( | |||
| 389 | ['â', '"'], # U+201C | |||||
| 390 | ['â', '"'], # U+201D | |||||
| 391 | ["\xe2\x80\x9c", '"'], # â | |||||
| 392 | ["\xe2\x80\x9d", '"'], # â | |||||
| 393 | ["\xe2\x80\x93", '–'], | |||||
| 394 | ["\xe2\x80\x94", '—'], | |||||
| 395 | ["\xe2\x80\x98", '''], # â | |||||
| 396 | ["\xe2\x80\x99", '''], # â | |||||
| 397 | ["\xe2\x80\xA6", '...'], # ⦠| |||||
| 398 | ['!', '!'], # Do this early before the ascii check, since it's an ascii character | |||||
| 399 | ); | |||||
| 400 | ||||||
| 401 | 289 | 264 | $string = _sub_map(\$string, \@byte_map); | |||
| 402 | ||||||
| 403 | 289 | 275 | unless($params->{'keep_apos'}) { | |||
| 404 | # Multi-byte curly apostrophes canât be combined in a char-class, so use | |||||
| 405 | # an alternation regex built from the key set â no /e eval needed. | |||||
| 406 | 278 | 467 | my %apos_map = ( | |||
| 407 | "'" => ''', | |||||
| 408 | "\x{2018}" => ''', # U+2018 left single quotation mark | |||||
| 409 | "\x{2019}" => ''', # U+2019 right single quotation mark | |||||
| 410 | "\x{0060}" => ''', # U+0060 grave accent used as apostrophe | |||||
| 411 | "\x98" => ''', | |||||
| 412 | ); | |||||
| 413 | 278 1390 | 240 966 | my $apos_re = join '|', map { quotemeta } keys %apos_map; | |||
| 414 | 278 | 3118 | $string =~ s/($apos_re)/$apos_map{$1}/g; | |||
| 415 | } | |||||
| 416 | ||||||
| 417 | 289 | 402 | if($string !~ /[^[:ascii:]]/) { | |||
| 418 | 109 | 262 | return $string; | |||
| 419 | } | |||||
| 420 | ||||||
| 421 | @byte_map = ( | |||||
| 422 | 180 | 2247 | ["\xc2\xa0", ' '], # Non breaking space | |||
| 423 | ["\xc2\xa3", '£'], | |||||
| 424 | ["\xc2\xa9", '©'], | |||||
| 425 | ["\xc2\xae", '®'], | |||||
| 426 | ["\xc3\xa2", 'â'], | |||||
| 427 | ["\xc3\xa4", 'ä'], | |||||
| 428 | ["\xc3\xa9", 'é'], | |||||
| 429 | ["\xc2\xaa", 'ª'], # ª | |||||
| 430 | ["\xc2\xab", '"'], # « | |||||
| 431 | ["\xc2\xbb", '"'], # » | |||||
| 432 | ["\xc3\x81", 'Á'], # Ã | |||||
| 433 | ["\xc3\x83", 'Î'], # Ã | |||||
| 434 | ["\xc3\x9e", 'Þ'], # Ã | |||||
| 435 | ["\xc3\xa0", 'à'], # Ã | |||||
| 436 | ["\xc3\xa1", 'á'], # á | |||||
| 437 | ["\xc3\xad", 'í'], # Ã | |||||
| 438 | ["\xc3\xb0", 'ð'], # ð | |||||
| 439 | ["\xc3\xba", 'ú'], # ú | |||||
| 440 | ["\xc3\xb4", 'ô'], # ô | |||||
| 441 | ["\xc3\xb6", 'ö'], | |||||
| 442 | ["\xc3\xb8", 'ø'], # ø | |||||
| 443 | ["\xc5\xa1", 'š'], | |||||
| 444 | ["\xc4\x8d", 'č'], | |||||
| 445 | ["\xc5\xbd", 'Ž'], | |||||
| 446 | ["\xc5\xbe", 'ž'], | |||||
| 447 | ["\xc3\xa5", 'å'], # Ã¥ | |||||
| 448 | ["\xc3\xa7", 'ç'], | |||||
| 449 | ["\xc3\xaf", 'ï'], # ï | |||||
| 450 | ["\xc3\xb3", 'ó'], | |||||
| 451 | ["\xc3\x96", 'Ö'], # Ã | |||||
| 452 | ["\xc3\xa8", 'è'], | |||||
| 453 | ["\xc3\x89", 'É'], | |||||
| 454 | ["\xc3\x9f", 'ß'], | |||||
| 455 | ["\xc3\xaa", 'ê'], | |||||
| 456 | ["\xc3\xab", 'ë'], | |||||
| 457 | ["\xc3\xae", 'î'], | |||||
| 458 | ["\xc3\xbb", 'û'], | |||||
| 459 | ["\xc3\xbc", 'ü'], # ü | |||||
| 460 | ["\xc3\xbe", 'þ'], # þ | |||||
| 461 | ["\xc5\x9b", 'ś'], | |||||
| 462 | ["\xc5\xa0", 'Š'], | |||||
| 463 | ["\xe2\x80\x93", '–'], | |||||
| 464 | ["\xe2\x80\x94", '—'], | |||||
| 465 | ["\xc3\xb1", 'ñ'], # ñ | |||||
| 466 | ["\xe2\x80\x9c", '"'], | |||||
| 467 | ["\xe2\x80\x9d", '"'], | |||||
| 468 | ["\xe2\x80\xa6", '...'], | |||||
| 469 | ["\xe2\x97\x8f", '●'], # â | |||||
| 470 | ["\N{U+00A0}", ' '], | |||||
| 471 | ["\N{U+00A3}", '£'], | |||||
| 472 | ["\N{U+00A9}", '©'], | |||||
| 473 | ["\N{U+00AA}", 'ª'], # ª | |||||
| 474 | ["\N{U+00AB}", '"'], # « | |||||
| 475 | ["\N{U+00AE}", '®'], | |||||
| 476 | ["\N{U+00B5}", 'µ'], # µ | |||||
| 477 | ["\N{U+00BB}", '"'], # » | |||||
| 478 | ["\N{U+00CE}", 'Î'], # Ã | |||||
| 479 | ["\N{U+00DE}", 'Þ'], # Ã | |||||
| 480 | ["\N{U+0161}", 'š'], | |||||
| 481 | ["\N{U+010D}", 'č'], | |||||
| 482 | ["\N{U+017D}", 'Ž'], | |||||
| 483 | ["\N{U+017E}", 'ž'], | |||||
| 484 | ["\N{U+00C9}", 'É'], | |||||
| 485 | ["\N{U+00D6}", 'Ö'], # Ã | |||||
| 486 | ["\N{U+00DF}", 'ß'], # Ã | |||||
| 487 | ["\N{U+00E1}", 'á'], # á | |||||
| 488 | ["\N{U+00E2}", 'â'], | |||||
| 489 | ["\N{U+00E4}", 'ä'], | |||||
| 490 | ["\N{U+00E5}", 'å'], # Ã¥ | |||||
| 491 | ["\N{U+00E0}", 'à'], # Ã | |||||
| 492 | ["\N{U+00E7}", 'ç'], # ç | |||||
| 493 | ["\N{U+00E8}", 'è'], | |||||
| 494 | ["\N{U+00E9}", 'é'], | |||||
| 495 | ["\N{U+00ED}", 'í'], # Ã | |||||
| 496 | ["\N{U+00EE}", 'î'], | |||||
| 497 | ["\N{U+00EF}", 'ï'], # ï | |||||
| 498 | ["\N{U+00F0}", 'ð'], # ð | |||||
| 499 | ["\N{U+00F1}", 'ñ'], # ñ | |||||
| 500 | ["\N{U+00F4}", 'ô'], # ô | |||||
| 501 | ["\N{U+00F6}", 'ö'], | |||||
| 502 | ["\N{U+00F8}", 'ø'], # ø | |||||
| 503 | ["\N{U+00FA}", 'ú'], # ú | |||||
| 504 | ["\N{U+00FC}", 'ü'], # ü | |||||
| 505 | ["\N{U+00FE}", 'þ'], # þ | |||||
| 506 | ["\N{U+00C1}", 'Á'], # Ã | |||||
| 507 | ["\N{U+00C9}", 'É'], | |||||
| 508 | ["\N{U+00CA}", 'ê'], | |||||
| 509 | ["\N{U+00EB}", 'ë'], | |||||
| 510 | ["\N{U+00F3}", 'ó'], | |||||
| 511 | ["\N{U+015B}", 'ś'], | |||||
| 512 | ["\N{U+00FB}", 'û'], | |||||
| 513 | ["\N{U+0160}", 'Š'], | |||||
| 514 | ["\N{U+2013}", '–'], | |||||
| 515 | ["\N{U+2014}", '—'], | |||||
| 516 | ["\N{U+2018}", '"'], | |||||
| 517 | ["\N{U+2019}", '"'], | |||||
| 518 | ["\N{U+201C}", '"'], | |||||
| 519 | ["\N{U+201D}", '"'], | |||||
| 520 | ["\N{U+2026}", '...'], # ⦠| |||||
| 521 | ["\N{U+2122}", '™'], # ⢠| |||||
| 522 | ["\xe2\x84\xa2", '™'], # ⢠UTF-8 | |||||
| 523 | ["\N{U+25CF}", '●'], # â | |||||
| 524 | ); | |||||
| 525 | ||||||
| 526 | 180 | 154 | $string = _sub_map(\$string, \@byte_map); | |||
| 527 | ||||||
| 528 | ||||||
| 529 | 180 | 2255 | @byte_map = ( | |||
| 530 | [ 'Ã', 'Á' ], | |||||
| 531 | [ 'Ã¥', 'å' ], | |||||
| 532 | [ 'ª', 'ª' ], | |||||
| 533 | [ 'Å¡', 'š' ], | |||||
| 534 | [ 'Å ', 'Š' ], | |||||
| 535 | [ 'Ä', 'č' ], | |||||
| 536 | [ 'Ž', 'Ž' ], | |||||
| 537 | [ 'ž', 'ž' ], | |||||
| 538 | [ 'Ã ', 'à' ], # Ã | |||||
| 539 | [ 'á', 'á' ], | |||||
| 540 | [ 'â', 'â' ], | |||||
| 541 | [ 'é', 'é' ], | |||||
| 542 | [ 'è', 'è' ], | |||||
| 543 | [ 'ç', 'ç' ], | |||||
| 544 | [ 'ê', 'ê' ], | |||||
| 545 | [ 'ë', 'ë' ], | |||||
| 546 | [ 'ð', 'ð' ], | |||||
| 547 | [ 'Ã', 'í' ], | |||||
| 548 | [ 'ï', 'ï' ], | |||||
| 549 | [ 'Ã', 'Î' ], | |||||
| 550 | [ '©', '©' ], | |||||
| 551 | [ '®', '®' ], | |||||
| 552 | [ 'ó', 'ó' ], | |||||
| 553 | [ 'ô', 'ô' ], | |||||
| 554 | [ 'ö', 'ö' ], | |||||
| 555 | [ 'ø', 'ø' ], | |||||
| 556 | [ 'Å', 'ś' ], | |||||
| 557 | [ 'Ã', 'Þ' ], | |||||
| 558 | [ 'þ', 'þ' ], | |||||
| 559 | [ 'û', 'û' ], | |||||
| 560 | [ 'ü', 'ü' ], | |||||
| 561 | [ 'ú', 'ú' ], | |||||
| 562 | [ 'µ', 'µ'], | |||||
| 563 | [ '£', '£' ], | |||||
| 564 | [ 'Ã', 'ß' ], | |||||
| 565 | [ 'â', '–' ], | |||||
| 566 | [ 'â', '—' ], | |||||
| 567 | [ 'ñ', 'ñ' ], | |||||
| 568 | [ 'â', '"' ], | |||||
| 569 | [ 'â', '"' ], | |||||
| 570 | [ '«', '"' ], | |||||
| 571 | [ '»', '"' ], | |||||
| 572 | [ 'â¦', '...' ], | |||||
| 573 | [ 'â¢', '™' ], | |||||
| 574 | [ 'â', '●' ], | |||||
| 575 | [ "\x80\$", ' ' ], | |||||
| 576 | ); | |||||
| 577 | ||||||
| 578 | 180 | 153 | $string = _sub_map(\$string, \@byte_map); | |||
| 579 | ||||||
| 580 | 180 | 217 | if($string =~ /[^[:ascii:]]/) { | |||
| 581 | 11 | 18 | $string = HTML::Entities::encode_entities_numeric($string, '\x80-\x{10FFFF}'); | |||
| 582 | 11 | 180 | if($string =~ /[^[:ascii:]]/) { | |||
| 583 | 7 | 19 | $complain->("TODO: wide_to_html($string)") if($complain); | |||
| 584 | # Sanitize non-ASCII to hex tokens before embedding in the error message | |||||
| 585 | 6 | 12 | $string =~ s{ | |||
| 586 | ([^[:ascii:]]) | |||||
| 587 | }{ | |||||
| 588 | 6 | 24 | '>>>>' . sprintf('%04X', ord($1)) . '<<<<' | |||
| 589 | }gex; | |||||
| 590 | 6 | 120 | carp "TODO: wide_to_html($string)"; | |||
| 591 | 6 | 912 | croak "BUG: wide_to_html($string)"; | |||
| 592 | } | |||||
| 593 | } | |||||
| 594 | ||||||
| 595 | 173 | 680 | return $string; | |||
| 596 | } | |||||
| 597 | ||||||
| 598 - 702 | =head2 wide_to_xml
Convert a Unicode or UTF-8 string into a pure-ASCII XML fragment. Every
non-ASCII character is replaced by a hexadecimal numeric entity
(e.g. C<é>). Only numeric entities are used because named HTML entities
such as C<é> are not defined in XML 1.0 outside of XHTML with a DTD.
Em-dashes and en-dashes are folded to a plain ASCII hyphen C<->.
Bare ampersands, angle brackets, and double-quotes are escaped so the output
is valid XML element content.
=head3 Arguments
All parameters are passed as a flat key-value list. The C<string> key may be
omitted when passing a bare positional string as the first argument.
See L</COMMON PARAMETERS> for C<string>, C<keep_hrefs>, and C<complain>.
This function does not accept C<keep_apos>.
=head3 Returns
A defined scalar string whose every character is in the ASCII range
(code points 0x00-0x7F). The empty string is returned unchanged.
=head3 EXAMPLE
use Encode::Wide qw(wide_to_xml);
# Accented characters become numeric entities
my $out = wide_to_xml(string => "SURN \x{017D}ganjar");
# => 'SURN Žganjar'
# En-dash and em-dash are folded to a plain hyphen
$out = wide_to_xml(string => "2020\x{2013}2026");
# => '2020-2026'
# Ampersands and angle brackets are XML-escaped
$out = wide_to_xml(string => 'a < b & c > 0');
# => 'a < b & c > 0'
# keep_hrefs: XML tags pass through; wide chars are still encoded
$out = wide_to_xml(
string => '<item lang="fr">Caf\x{E9}</item>',
keep_hrefs => 1,
);
# => '<item lang="fr">Café</item>'
# Scalar reference input
my $text = "caf\x{E9}";
$out = wide_to_xml(string => \$text);
# => 'café'
=head3 MESSAGES
=over 4
=item C<Usage: wide_to_xml() string not set>
B<Fatal> (via C<croak>). The C<string> parameter was C<undef>.
Resolution: pass a defined scalar or scalar reference.
=item C<TODO: wide_to_xml(E<lt>hex-tokens...E<gt>)>
B<Warning> (via C<carp>). A character survived all three byte_map passes.
The hex tokens in the message identify the unhandled codepoint(s).
Resolution: add the character to the appropriate byte_map array, or file a bug
report at L<https://rt.cpan.org/Public/Dist/Display.html?Name=Encode-Wide>.
=item C<BUG: wide_to_xml(E<lt>hex-tokens...E<gt>)>
B<Fatal> (via C<croak>), always preceded by the C<TODO> warning above.
This should never occur in normal use; it indicates a gap in the XML character
tables. Unlike C<wide_to_html>, there is no numeric-entity fallback for XML
because there is no safe generic fallback that is valid in all XML contexts.
=back
=head3 API SPECIFICATION
=head4 Input
{
string => { type => SCALAR | SCALARREF, required => 1, defined => 1 },
keep_hrefs => { type => BOOLEAN, optional => 1, default => 0 },
complain => { type => CODEREF, optional => 1 },
}
=head4 Output
{ type => SCALAR, constraint => sub { $_[0] !~ /[^[:ascii:]]/ } }
=head3 PSEUDOCODE
1. Unless keep_hrefs: decode HTML entities via HTML::Entities::decode
and the four extra named entities (č ž Ž Š)
2. Escape bare & not followed by a valid entity name
(possessive ++ quantifier prevents ReDoS backtracking)
3. Unless keep_hrefs: escape <, >, and " using %_HTML_ESCAPE (no /e eval)
4. First byte_map pass: curly quotes -> ", dashes -> -, apostrophes
5. Early return if the string is now pure ASCII
6. Second byte_map pass: raw UTF-8 byte sequences -> numeric XML entities
7. Third byte_map pass: Perl Unicode chars (\N{U+...}) -> numeric XML entities
8. If non-ASCII still remains: invoke complain callback, carp a TODO warning,
then croak a BUG error
=cut | |||||
| 703 | ||||||
| 704 | # See https://www.compart.com/en/unicode/U+0161 etc. | |||||
| 705 | # https://www.compart.com/en/unicode/U+00EB | |||||
| 706 | sub wide_to_xml | |||||
| 707 | { | |||||
| 708 | 275 | 106893 | my $params = Params::Get::get_params('string', @_); | |||
| 709 | ||||||
| 710 | 274 | 2877 | my $string = $params->{'string'}; | |||
| 711 | 274 | 162 | my $complain = $params->{'complain'}; | |||
| 712 | ||||||
| 713 | 274 | 233 | if(!defined($string)) { | |||
| 714 | 5 | 35 | croak 'Usage: wide_to_xml() string not set'; | |||
| 715 | } | |||||
| 716 | ||||||
| 717 | 269 | 220 | if(ref($string) eq 'SCALAR') { | |||
| 718 | 21 21 | 12 13 | $string = ${$string}; | |||
| 719 | } | |||||
| 720 | ||||||
| 721 | ||||||
| 722 | # SECURITY: skip entity-decoding when keep_hrefs is set â same rationale as | |||||
| 723 | # wide_to_html: decoded payloads bypass re-escaping and produce XSS output. | |||||
| 724 | 269 | 225 | unless($params->{'keep_hrefs'}) { | |||
| 725 | 258 | 416 | $string = HTML::Entities::decode($string); | |||
| 726 | ||||||
| 727 | # Decode the four named entities HTML::Entities::decode misses | |||||
| 728 | 258 | 604 | $string =~ s/($_EXTRA_ENTITY_RE)/$_EXTRA_ENTITY_MAP{$1}/g; | |||
| 729 | } | |||||
| 730 | ||||||
| 731 | # Possessive ++ prevents O(n^2) backtracking (ReDoS) on inputs like | |||||
| 732 | # "&aaaaaa..." with no closing semicolon. | |||||
| 733 | 269 | 200 | $string =~ s/&(?![A-Za-z#0-9]++;)/&/g; | |||
| 734 | ||||||
| 735 | 269 | 195 | unless($params->{'keep_hrefs'}) { | |||
| 736 | # Escape ASCII markup chars; %_HTML_ESCAPE eliminates the /e eval flag. | |||||
| 737 | 258 | 253 | $string =~ s/([<>"])/$_HTML_ESCAPE{$1}/g; | |||
| 738 | } | |||||
| 739 | ||||||
| 740 | # $string =~ s/â/'/g; | |||||
| 741 | # $string =~ s/â/'/g; | |||||
| 742 | # $string =~ s/â/'/g; | |||||
| 743 | # $string =~ s/â/'/g; | |||||
| 744 | # $string =~ s/\x98/'/g; | |||||
| 745 | # $string =~ s/['âââ\x98]/'/g; | |||||
| 746 | ||||||
| 747 | # Table of byte-sequences->entities | |||||
| 748 | 269 | 680 | my @byte_map = ( | |||
| 749 | [ "\xe2\x80\x9c", '"' ], # â | |||||
| 750 | [ "\xe2\x80\x9d", '"' ], # â | |||||
| 751 | [ 'â', '"' ], # U+201C | |||||
| 752 | [ 'â', '"' ], # U+201D | |||||
| 753 | [ "\xe2\x80\x93", '-' ], # ndash | |||||
| 754 | [ "\xe2\x80\x94", '-' ], # mdash | |||||
| 755 | [ "\xe2\x80\x98", ''' ], # â | |||||
| 756 | [ "\xe2\x80\x99", ''' ], # â | |||||
| 757 | [ "\xe2\x80\xA6", '...' ], # ⦠| |||||
| 758 | [ "'", ''' ], | |||||
| 759 | [ 'â', ''' ], | |||||
| 760 | [ 'â', ''' ], | |||||
| 761 | [ 'â', ''' ], | |||||
| 762 | [ "\x98", ''' ], | |||||
| 763 | ); | |||||
| 764 | ||||||
| 765 | 269 | 227 | $string = _sub_map(\$string, \@byte_map); | |||
| 766 | ||||||
| 767 | # DEAD CODE: the %entity_map below has keys that are multi-character HTML | |||||
| 768 | # entity strings (e.g. '©', 'Á'). The s{(.)}{...}gex loop | |||||
| 769 | # that follows matches one character at a time; a single char can never | |||||
| 770 | # equal a multi-char key, so the true branch is unreachable. | |||||
| 771 | # By the time the string reaches here, HTML::Entities::decode has already | |||||
| 772 | # converted all recognised named entities to their Unicode equivalents, | |||||
| 773 | # which the byte_map passes below encode correctly. | |||||
| 774 | # Additional bugs in the removed block: 'ú' => '�FA;' (decimal, | |||||
| 775 | # not hex) and 'û' => 'ô' (maps to o-circumflex, not u-circumflex). | |||||
| 776 | # This block has been commented out to remove dead code and reach 100% | |||||
| 777 | # branch coverage. See t/extended_tests.t section 3 for validation. | |||||
| 778 | # | |||||
| 779 | # %entity_map = ( | |||||
| 780 | # '©' => '©', | |||||
| 781 | # 'Á' => 'Á', | |||||
| 782 | # 'č' => 'č', | |||||
| 783 | # ... | |||||
| 784 | # '!' => '!', | |||||
| 785 | # ); | |||||
| 786 | # $string =~ s{(.)}{ | |||||
| 787 | # my $cp = $1; | |||||
| 788 | # exists $entity_map{$cp} | |||||
| 789 | # ? $entity_map{$cp} | |||||
| 790 | # : $cp | |||||
| 791 | # }gex; | |||||
| 792 | ||||||
| 793 | 269 | 332 | if($string !~ /[^[:ascii:]]/) { | |||
| 794 | 74 | 175 | return $string; | |||
| 795 | } | |||||
| 796 | ||||||
| 797 | @byte_map = ( | |||||
| 798 | 195 | 2397 | ["\xc2\xa0", ' '], # Non breaking space | |||
| 799 | ["\xc2\xa3", '£'], # £ | |||||
| 800 | ["\xc2\xa9", '©'], | |||||
| 801 | ["\xc2\xaa", 'ª'], # ª | |||||
| 802 | ["\xc2\xab", '"'], # « | |||||
| 803 | ["\xc2\xae", '®'], | |||||
| 804 | ["\xc3\x81", 'Á'], # Ã | |||||
| 805 | ["\xc3\x8e", 'Î'], # Ã | |||||
| 806 | ["\xc3\xa0", 'à'], # Ã | |||||
| 807 | ["\xc3\xa1", 'á'], # á | |||||
| 808 | ["\xc3\xa5", 'å'], # Ã¥ | |||||
| 809 | ["\xc3\xa9", 'é'], | |||||
| 810 | ["\xc3\xaf", 'ï'], # ï | |||||
| 811 | ["\xc3\xb1", 'ñ'], # ntilde ñ | |||||
| 812 | ["\xc5\xa1", 'š'], | |||||
| 813 | ["\xc4\x8d", 'č'], | |||||
| 814 | ["\xc5\xbd", 'Ž'], # Ž | |||||
| 815 | ["\xc5\xbe", 'ž'], # ž | |||||
| 816 | ["\xc3\x96", 'Ö'], # Ã | |||||
| 817 | ["\xc3\x9e", 'Þ'], # Ã | |||||
| 818 | ["\xc3\x9f", 'ß'], # Ã | |||||
| 819 | ["\xc3\xa2", 'â'], # â | |||||
| 820 | ["\xc3\xad", 'í'], # Ã | |||||
| 821 | ["\xc3\xa4", 'ä'], # ä | |||||
| 822 | ["\xc3\xa7", 'ç'], # ç | |||||
| 823 | ["\xc3\xb0", 'ð'], # ð | |||||
| 824 | ["\xc3\xb3", 'ó'], # ó | |||||
| 825 | ["\xc3\xb8", 'ø'], # ø | |||||
| 826 | ["\xc3\xbc", 'ü'], # ü | |||||
| 827 | ["\xc3\xbe", 'þ'], # þ | |||||
| 828 | ["\xc3\xa8", 'è'], # è | |||||
| 829 | ["\xc3\xee", 'î'], | |||||
| 830 | ["\xc3\xb4", 'ô'], # ô | |||||
| 831 | ["\xc3\xb6", 'ö'], # ö | |||||
| 832 | ["\xc3\x89", 'É'], | |||||
| 833 | ["\xc3\xaa", 'ê'], | |||||
| 834 | ["\xc3\xab", 'ë'], # eumlaut | |||||
| 835 | ["\xc3\xba", 'ú'], # ú | |||||
| 836 | ["\xc3\xbb", '»'], # û - ucirc | |||||
| 837 | ["\xc5\x9b", 'ś'], # Å - sacute | |||||
| 838 | ["\xc5\xa0", 'Š'], | |||||
| 839 | ["\xe2\x80\x93", '-'], | |||||
| 840 | ["\xe2\x80\x94", '-'], | |||||
| 841 | ["\xe2\x80\x9c", '"'], | |||||
| 842 | ["\xe2\x80\x9d", '"'], | |||||
| 843 | ["\xe2\x80\xa6", '...'], | |||||
| 844 | ["\xe2\x97\x8f", '●'], # â | |||||
| 845 | ["\xe3\xb1", 'ñ'], # ntilde ñ - what's this one? | |||||
| 846 | ||||||
| 847 | ["\N{U+00A0}", ' '], | |||||
| 848 | ["\N{U+010D}", 'č'], | |||||
| 849 | ["\N{U+00AB}", '"'], # « | |||||
| 850 | ["\N{U+00AE}", '®'], # ® | |||||
| 851 | ["\N{U+00B5}", 'µ'], # µ | |||||
| 852 | ["\N{U+00C1}", 'Á'], # Ã | |||||
| 853 | ["\N{U+00CE}", 'Î'], # Ã | |||||
| 854 | ["\N{U+00DE}", 'Þ'], # Ã | |||||
| 855 | ["\N{U+00E0}", 'à'], # Ã | |||||
| 856 | ["\N{U+00E4}", 'ä'], # ä | |||||
| 857 | ["\N{U+00E5}", 'å'], # Ã¥ | |||||
| 858 | ["\N{U+00EA}", 'ê'], | |||||
| 859 | ["\N{U+00ED}", 'í'], | |||||
| 860 | ["\N{U+00EE}", 'î'], | |||||
| 861 | ["\N{U+00FE}", 'þ'], # þ | |||||
| 862 | ["\N{U+00C9}", 'É'], | |||||
| 863 | ["\N{U+017D}", 'Ž'], # Ž | |||||
| 864 | ["\N{U+017E}", 'ž'], # ž | |||||
| 865 | ["\N{U+00D6}", 'Ö'], # Ã | |||||
| 866 | ["\N{U+00DF}", 'ß'], # Ã | |||||
| 867 | ["\N{U+00E1}", 'á'], # á - aacute | |||||
| 868 | ["\N{U+00E2}", 'â'], | |||||
| 869 | ["\N{U+00E8}", 'è'], # è | |||||
| 870 | ["\N{U+00EF}", 'ï'], # ï | |||||
| 871 | ["\N{U+00F0}", 'ð'], # ð | |||||
| 872 | ["\N{U+00F1}", 'ñ'], # ñ | |||||
| 873 | ["\N{U+00F3}", 'ó'], # ó | |||||
| 874 | ["\N{U+00F4}", 'ô'], # ô | |||||
| 875 | ["\N{U+00F6}", 'ö'], # ö | |||||
| 876 | ["\N{U+00F8}", 'ø'], # ø | |||||
| 877 | ["\N{U+00FA}", 'ú'], # ú | |||||
| 878 | ["\N{U+00FC}", 'ü'], # ü | |||||
| 879 | ["\N{U+015B}", 'ś'], # Å | |||||
| 880 | ["\N{U+00E9}", 'é'], | |||||
| 881 | ["\N{U+00E7}", 'ç'], # ç | |||||
| 882 | ["\N{U+00EB}", 'ë'], # ë | |||||
| 883 | ["\N{U+00FB}", 'û'], # û | |||||
| 884 | ["\N{U+0160}", 'Š'], | |||||
| 885 | ["\N{U+0161}", 'š'], | |||||
| 886 | ["\N{U+00A3}", '£'], # £ | |||||
| 887 | ["\N{U+00A9}", '©'], # © | |||||
| 888 | ["\N{U+2013}", '-'], | |||||
| 889 | ["\N{U+2014}", '-'], | |||||
| 890 | ["\N{U+2018}", '"'], | |||||
| 891 | ["\N{U+2019}", '"'], | |||||
| 892 | ["\N{U+201C}", '"'], | |||||
| 893 | ["\N{U+201D}", '"'], | |||||
| 894 | ["\N{U+2026}", '...'], # ⦠| |||||
| 895 | ["\N{U+2122}", '™'], # ⢠| |||||
| 896 | ["\xe2\x84\xa2", '™'], # ⢠UTF-8 | |||||
| 897 | ["\N{U+25CF}", '●'], # â | |||||
| 898 | ); | |||||
| 899 | ||||||
| 900 | 195 | 161 | $string = _sub_map(\$string, \@byte_map); | |||
| 901 | ||||||
| 902 | 195 | 2347 | @byte_map = ( | |||
| 903 | ["'", '''], | |||||
| 904 | ["\x98", '''], | |||||
| 905 | ['©', '©'], | |||||
| 906 | ['ª', 'ª'], | |||||
| 907 | ['®', '®'], | |||||
| 908 | ['Ã¥', 'å'], | |||||
| 909 | ['Å¡', 'š'], | |||||
| 910 | ['Ä', 'č'], | |||||
| 911 | ['Ž', 'Ž'], | |||||
| 912 | ['ž', 'ž'], | |||||
| 913 | ['£', '£'], | |||||
| 914 | ['µ', 'µ'], | |||||
| 915 | ['Ã ', 'à'], # Ã | |||||
| 916 | ['á', 'á'], # á | |||||
| 917 | ['â', 'â'], | |||||
| 918 | ['ä', 'ä'], # ä | |||||
| 919 | ['Ã', 'Á'], # Ã | |||||
| 920 | ['Ã', 'Ö'], | |||||
| 921 | ['Ã', 'ß'], | |||||
| 922 | ['ç', 'ç'], | |||||
| 923 | ['è', 'è'], | |||||
| 924 | ['é', 'é'], | |||||
| 925 | ['ê', 'ê'], | |||||
| 926 | ['ë', 'ë'], | |||||
| 927 | ['Ã', 'í'], | |||||
| 928 | ['ï', 'ï'], | |||||
| 929 | ['Ã', 'Î'], # Ã | |||||
| 930 | ['Ã', 'Þ'], # Ã | |||||
| 931 | ['ð', 'ð'], # ð | |||||
| 932 | ['ø', 'ø'], # ø | |||||
| 933 | ['û', 'û'], | |||||
| 934 | ['ñ', 'ñ'], | |||||
| 935 | ['ú', 'ú'], | |||||
| 936 | ['ü', 'ü'], | |||||
| 937 | ['þ', 'þ'], # þ | |||||
| 938 | ['â', '"'], | |||||
| 939 | ['â', '"'], | |||||
| 940 | ['«', '"'], | |||||
| 941 | ['»', '"'], | |||||
| 942 | ['â', '-'], | |||||
| 943 | ['â', '-'], | |||||
| 944 | ['â¦', '...'], | |||||
| 945 | ['â¢', '™'], | |||||
| 946 | ['â', '●'], | |||||
| 947 | ["\x80\$", ' '], | |||||
| 948 | ); | |||||
| 949 | ||||||
| 950 | 195 | 167 | $string = _sub_map(\$string, \@byte_map); | |||
| 951 | ||||||
| 952 | 195 | 211 | if($string =~ /[^[:ascii:]]/) { | |||
| 953 | 10 | 19 | $complain->("TODO: wide_to_xml($string)") if($complain); | |||
| 954 | # Sanitize non-ASCII to hex tokens before embedding in the error message | |||||
| 955 | 10 | 36 | $string =~ s{ | |||
| 956 | ([^[:ascii:]]) | |||||
| 957 | }{ | |||||
| 958 | 11 | 36 | '>>>>' . sprintf('%04X', ord($1)) . '<<<<' | |||
| 959 | }gex; | |||||
| 960 | 10 | 126 | carp "TODO: wide_to_xml($string)"; | |||
| 961 | 10 | 1421 | croak "BUG: wide_to_xml($string)"; | |||
| 962 | } | |||||
| 963 | 185 | 674 | return $string; | |||
| 964 | } | |||||
| 965 | ||||||
| 966 | # _sub_map -- apply a list of [from, to] substitutions in a single pass. | |||||
| 967 | # | |||||
| 968 | # Purpose: Replace every occurrence of each 'from' key with its 'to' value. | |||||
| 969 | # Longer keys take priority over shorter ones (longest-match-first). | |||||
| 970 | # Entry: $_[0] scalar-ref to string; $_[1] arrayref of [from, to] pairs. | |||||
| 971 | # Duplicate 'from' keys: the first definition wins. | |||||
| 972 | # Exit: Returns a new string (the scalar-ref argument is not modified). | |||||
| 973 | # Side Effects: None. | |||||
| 974 | sub _sub_map | |||||
| 975 | { | |||||
| 976 | 1314 1314 | 7687 799 | my $string = ${$_[0]}; | |||
| 977 | 1314 | 648 | my $byte_map = $_[1]; | |||
| 978 | ||||||
| 979 | # Build the alternation regex, longest key first to prevent partial matches | |||||
| 980 | my $pattern = join '|', | |||||
| 981 | 61385 | 34683 | map { quotemeta($_->[0]) } | |||
| 982 | 110539 | 50436 | sort { length($b->[0]) <=> length($a->[0]) } | |||
| 983 | 1314 1314 | 668 1343 | @{$byte_map}; | |||
| 984 | ||||||
| 985 | # Pre-build a hash for O(1) lookup during substitution. | |||||
| 986 | # Iterate in reverse so that the first definition in @byte_map wins on duplicate keys. | |||||
| 987 | 1314 | 1867 | my %map; | |||
| 988 | 1314 1314 | 637 754 | for my $pair (reverse @{$byte_map}) { | |||
| 989 | 61385 | 36267 | $map{$pair->[0]} = $pair->[1]; | |||
| 990 | } | |||||
| 991 | ||||||
| 992 | # No /e flag: hash dereference is a simple value interpolation, not code. | |||||
| 993 | 1314 | 62180 | $string =~ s/($pattern)/$map{$1}/g; | |||
| 994 | ||||||
| 995 | 1314 | 5933 | return $string; | |||
| 996 | } | |||||
| 997 | ||||||
| 998 - 1152 | =head1 SECURITY
=head2 XSS via entity decode and keep_hrefs
By default both functions call C<HTML::Entities::decode> as the first pipeline
step, normalising input like C<<b>> to C<< <b> >> before re-escaping it.
This round-trip is safe when C<keep_hrefs> is false because the re-escape step
then converts C<< < >> and C<< > >> back to C<<> and C<>>.
When C<keep_hrefs =E<gt> 1> is set, the re-escape step is skipped so that
existing markup survives intact. If the decode step still ran, a malicious
input such as C<<script>alert(1)</script>> would become the raw
string C<< <script>alert(1)</script> >> and pass through to the output
unescaped, creating a stored XSS vector.
B<Fix applied in 0.07:> when C<keep_hrefs> is true, the decode step is also
skipped. The pipeline treats the input as already-trusted HTML; wide
characters are still encoded, but entity normalisation becomes the caller's
responsibility.
=head2 ReDoS in bare-ampersand substitution
The substitution that escapes bare C<&> characters uses a negative lookahead
to distinguish bare ampersands from valid entity references. A naive
backtracking quantifier inside that lookahead creates O(n^2) work for inputs
such as C<&aaaaa...X> (many word characters, no closing semicolon).
B<Fix applied in 0.07:> the character class inside the lookahead uses a
possessive quantifier C<[A-Za-z#0-9]++>, which commits matches and prevents
backtracking. Perl 5.10 or later is required, consistent with the declared
C<MIN_PERL_VERSION>.
=head2 Eval-free substitutions
All substitutions in this module use plain C</g> rather than C</ge> (evaluate
replacement as Perl code). The C</e> flag was present in earlier versions but
was unnecessary: hash lookups are value interpolation, not executable code.
Removing C</e> eliminates a class of potential code-injection issues should a
future change inadvertently expose user-controlled data in the replacement
expression.
=head1 LIMITATIONS
=over 4
=item Character coverage is hand-maintained
Both functions use explicit C<@byte_map> tables organised into three passes
(raw UTF-8 bytes, C<\N{U+...}> named chars, literal Unicode source chars).
Characters not covered by these tables fall back to
C<HTML::Entities::encode_entities_numeric> in C<wide_to_html>, or trigger a
fatal C<BUG:> error in C<wide_to_xml> (XML has no safe generic numeric
fallback). To add a missing character, extend all three passes for the
relevant function and add a regression test in C<t/30-basics.t>.
=item No C<< <script> >> or C<< <style> >> awareness
C<wide_to_html> encodes wide characters uniformly regardless of context. It
does not detect content inside C<< <script> >> or C<< <style> >> blocks, so
passing a complete HTML document through this function will corrupt embedded
scripts and stylesheets. Feed only text fragments or attribute values, not
full documents.
=item XML numeric entity format uses a minimal hex width
The XML pipeline outputs C<é> (three hex digits with one leading zero
for values below 0x100) rather than the canonical four-digit form C<é>.
Both representations are valid XML 1.0. Consumers that perform strict byte-
level comparison of entity strings should normalise to a consistent width
before comparing.
=item Raw binary input is not supported
The module assumes its input is either a Perl Unicode string (internal C<utf8>
flag set) or a valid UTF-8 byte string. Passing arbitrary binary data or
text in a single-byte encoding other than Latin-1 will produce incorrect
output or trigger decoding errors. Decode the input with L<Encode/decode>
before calling these functions.
=item C<keep_hrefs> shifts trust to the caller
When C<keep_hrefs =E<gt> 1> is set, entity-decoding is suppressed and markup
characters pass through unescaped. The caller must guarantee that the input
does not contain untrusted content that could produce XSS output.
=back
=head1 SEE ALSO
=over 4
=item * L<Test Dashboard|https://nigelhorne.github.io/Encode-Wide/coverage/>
=item * L<HTML::Entities> â the standard module for HTML entity encoding and decoding
=item * L<Encode> â Perl's core character encoding framework
=item * L<XML::Entities> â decodes XML named entities (the inverse of wide_to_xml)
=item * L<Unicode::Escape> â alternative Unicode escaping approaches
=item * L<https://www.compart.com/en/unicode/> â Unicode character reference
=back
=head1 SUPPORT
Please report bugs and feature requests through the RT bug tracker:
https://rt.cpan.org/Public/Dist/Display.html?Name=Encode-Wide
Or by email: C<bug-encode-wide at rt.cpan.org>
You will be notified automatically of progress on your report.
=head1 FORMAL SPECIFICATION
=head2 wide_to_html
Let S be the input string, S' the output string.
â c â S' : ord(c) ⤠0x7F (ASCII-only output)
S = "" â¹ S' = "" (empty pass-through)
keep_hrefs = 0 â¹ "<" â S' â§ ">" â S' â§ â bare " in S'
keep_apos = 0 â¹ â bare apostrophe in S'
‰ bare & in S' (& appears only as part of a valid &name; or &#xNN; entity)
string = undef â¹ croak("Usage: wide_to_html() string not set")
=head2 wide_to_xml
Let S be the input string, S' the output string.
â c â S' : ord(c) ⤠0x7F (ASCII-only output)
S = "" â¹ S' = "" (empty pass-through)
keep_hrefs = 0 â¹ "<" â S' â§ ">" â S' â§ â bare " in S'
U+2013 â S â¹ "-" â S' â§ U+2013 â S' (en-dash collapsed)
U+2014 â S â¹ "-" â S' â§ U+2014 â S' (em-dash collapsed)
‰ bare & in S' (& appears only as part of a valid &name; or &#xNN; entity)
string = undef â¹ croak("Usage: wide_to_xml() string not set")
=head1 AUTHOR
Nigel Horne, C<< <njh at nigelhorne.com> >>
=head1 LICENCE AND COPYRIGHT
Copyright 2025-2026 Nigel Horne.
This library is free software; you may redistribute it and/or modify it under
the same terms as Perl itself (GPL version 2 or later).
If you use this module, please let me know at
C<njh at nigelhorne.com>.
=cut | |||||
| 1153 | ||||||
| 1154 | 1; | |||||