1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 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 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
|
use strict;
use 5.006;
package HTML::Restrict;
use version;
our $VERSION = 'v3.0.2';
use Carp qw( croak );
use Data::Dump qw( dump );
use HTML::Parser ();
use HTML::Entities qw( encode_entities );
use Types::Standard 1.000001 qw[ Bool HashRef ArrayRef CodeRef ];
use List::Util 1.33 qw( any none );
use Scalar::Util qw( reftype weaken );
use Sub::Quote qw( quote_sub );
use URI ();
use Moo 1.002000;
use namespace::clean;
has allow_comments => (
is => 'rw',
isa => Bool,
default => 0,
);
has allow_declaration => (
is => 'rw',
isa => Bool,
default => 0,
);
has create_newlines => (
is => 'rw',
isa => Bool,
default => 0,
);
has debug => (
is => 'rw',
isa => Bool,
default => 0,
);
has parser => (
is => 'ro',
lazy => 1,
builder => '_build_parser',
);
has rules => (
is => 'rw',
isa => HashRef,
required => 0,
default => quote_sub(' {} '),
trigger => \&_build_parser,
reader => 'get_rules',
writer => 'set_rules',
);
has strip_enclosed_content => (
is => 'rw',
isa => ArrayRef,
default => sub { [ 'script', 'style' ] },
);
has replace_img => (
is => 'rw',
isa => Bool | CodeRef,
default => 0,
);
has trim => (
is => 'rw',
isa => Bool,
default => 1,
);
has filter_text => (
is => 'rw',
isa => Bool | CodeRef,
default => 1,
);
has uri_schemes => (
is => 'rw',
isa => ArrayRef,
required => 0,
default => sub { [ undef, 'http', 'https' ] },
reader => 'get_uri_schemes',
writer => 'set_uri_schemes',
);
has _processed => (
is => 'rw',
isa => quote_sub(
q{
die "$_[0] is not false or a string!"
unless !defined($_[0]) || $_[0] eq "" || "$_[0]" eq '0' || ref(\$_[0]) eq 'SCALAR'
}
),
clearer => '_clear_processed',
);
has _stripper_stack => (
is => 'rw',
isa => ArrayRef,
default => sub { [] },
);
sub _build_parser {
my $self = shift;
my $rules = shift;
# don't allow any upper case tag or attribute names
# these rules would otherwise silently be ignored
if ($rules) {
foreach my $tag_name ( keys %{$rules} ) {
if ( lc $tag_name ne $tag_name ) {
croak 'All tag names must be lower cased';
}
if ( reftype $rules->{$tag_name} eq 'ARRAY' ) {
my @attr_names;
foreach my $attr_item ( @{ $rules->{$tag_name} } ) {
ref $attr_item eq 'HASH'
? push( @attr_names, keys(%$attr_item) )
: push( @attr_names, $attr_item );
}
for (@attr_names) {
croak 'All attribute names must be lower cased'
if lc $_ ne $_;
}
}
}
}
weaken($self);
return HTML::Parser->new(
empty_element_tags => 1,
start_h => [
sub {
my ( $p, $tagname, $attr, $text ) = @_;
print "starting tag: $tagname", "\n" if $self->debug;
my $more = q{};
if ( any { $_ eq $tagname } keys %{ $self->get_rules } ) {
print dump $attr if $self->debug;
foreach my $source_type ( 'href', 'src', 'cite' ) {
my $link = $attr->{$source_type};
# Remove unprintable ASCII control characters, which
# are 0..31. These characters are not valid in URLs,
# but they can prevent the URI parser from recognizing
# the scheme when they are used as leading characters.
# Browsers will helpfully ignore some of them, meaning
# that some of these characters (particularly 1..8 and
# 14..31) can be used to defeat HTML::Restrict when
# used as leading characters in a link. In our case we
# will strip them all regardless of where they are in
# the URL. See
# https://github.com/oalders/html-restrict/issues/30
# https://url.spec.whatwg.org/
# https://infra.spec.whatwg.org/#c0-control
if ($link) {
# C0 control chars (decimal 0..31)
# sort of like $link =~ s/[[:^print:]]//g
$link =~ s/[\00-\037]|&#x?0+;/ /g;
my $url = URI->new($link);
if ( defined $url->scheme ) {
delete $attr->{$source_type}
if none { $_ eq $url->scheme }
grep { defined }
@{ $self->get_uri_schemes };
}
else { # relative URL
delete $attr->{$source_type}
unless grep { !defined }
@{ $self->get_uri_schemes };
}
}
}
foreach
my $attr_item ( @{ $self->get_rules->{$tagname} } ) {
if ( ref $attr_item eq 'HASH' ) {
# validate or munge with regex or coderef contraints
#
for my $attr_name (
sort grep exists $attr->{$_},
keys %$attr_item
) {
my $rule = $attr_item->{$attr_name};
my $value = $attr->{$attr_name};
if ( ref $rule eq 'CODE' ) {
$value = $rule->($value);
next
if !defined $value;
}
elsif ( $value =~ $rule ) {
# ok
}
else {
next;
}
$more .= qq[ $attr_name="]
. encode_entities($value) . q{"};
}
}
else {
my $attr_name = $attr_item;
if ( exists $attr->{$attr_name} ) {
my $value
= encode_entities( $attr->{$attr_name} );
$more .= qq[ $attr_name="$value" ]
unless $attr_name eq '/';
}
}
}
# closing slash should (naturally) close the tag
if ( exists $attr->{'/'} && $attr->{'/'} eq '/' ) {
$more .= ' /';
}
my $elem = "<$tagname $more>";
$elem =~ s{\s*>}{>}gxms;
$elem =~ s{\s+}{ }gxms;
$self->_processed( ( $self->_processed || q{} ) . $elem );
}
elsif ( $tagname eq 'img' && $self->replace_img ) {
my $alt;
if ( ref $self->replace_img ) {
$alt = $self->replace_img->( $tagname, $attr, $text );
}
else {
$alt
= defined( $attr->{alt} )
? ": $attr->{alt}"
: q{};
$alt = "[IMAGE$alt]";
}
$self->_processed( ( $self->_processed || q{} ) . $alt );
}
elsif ( $tagname eq 'br' && $self->create_newlines ) {
$self->_processed( ( $self->_processed || q{} ) . "\n" );
}
elsif ( $tagname eq 'p' && $self->create_newlines ) {
$self->_processed(
( $self->_processed || q{} ) . "\n\n" );
}
elsif ( any { $_ eq $tagname }
@{ $self->strip_enclosed_content } ) {
print "adding $tagname to strippers" if $self->debug;
push @{ $self->_stripper_stack }, $tagname;
}
},
'self,tagname,attr,text'
],
end_h => [
sub {
my ( $p, $tagname, $attr, $text ) = @_;
print "end: $text\n" if $self->debug;
if ( any { $_ eq $tagname } keys %{ $self->get_rules } ) {
$self->_processed( ( $self->_processed || q{} ) . $text );
}
elsif ( any { $_ eq $tagname } @{ $self->_stripper_stack } ) {
$self->_delete_tag_from_stack($tagname);
}
},
'self,tagname,attr,text'
],
text_h => [
sub {
my ( $p, $text ) = @_;
print "text: $text\n" if $self->debug;
if ( ref $self->filter_text ) {
$text = $self->filter_text->($text);
}
elsif ( $self->filter_text ) {
$text = _fix_text_encoding($text);
}
if ( !@{ $self->_stripper_stack } ) {
$self->_processed( ( $self->_processed || q{} ) . $text );
}
},
'self,text'
],
comment_h => [
sub {
my ( $p, $text ) = @_;
print "comment: $text\n" if $self->debug;
if ( $self->allow_comments ) {
$self->_processed( ( $self->_processed || q{} ) . $text );
}
},
'self,text'
],
declaration_h => [
sub {
my ( $p, $text ) = @_;
print "declaration: $text\n" if $self->debug;
if ( $self->allow_declaration ) {
$self->_processed( ( $self->_processed || q{} ) . $text );
}
},
'self,text'
],
);
}
sub process {
my $self = shift;
# returns undef if no value was passed
return if !@_;
return $_[0] if !$_[0];
my ($content) = @_;
die 'content must be a string!'
unless ref( \$content ) eq 'SCALAR';
$self->_clear_processed;
my $parser = $self->parser;
$parser->parse($content);
$parser->eof;
my $text = $self->_processed;
if ( $self->trim && $text ) {
$text =~ s{\A\s*}{}gxms;
$text =~ s{\s*\z}{}gxms;
}
$self->_processed($text);
# ensure stripper stack is reset in case of broken html
$self->_stripper_stack( [] );
return $self->_processed;
}
# strip_enclosed_content tags could be nested in the source HTML, so we
# maintain a stack of these tags.
sub _delete_tag_from_stack {
my $self = shift;
my $closing_tag = shift;
my $found = 0;
my @tag_list = ();
foreach my $tag ( reverse @{ $self->_stripper_stack } ) {
if ( $tag eq $closing_tag && $found == 0 ) {
$found = 1;
next;
}
push @tag_list, $tag;
}
$self->_stripper_stack( [ reverse @tag_list ] );
return;
}
# regex for entities that don't require a terminating semicolon
my ($short_entity_re)
= map qr/$_/i,
join '|',
'#x[0-9a-f]+',
'#[0-9]+',
grep !/;\z/,
sort keys %HTML::Entities::entity2char;
# semicolon required
my ($complete_entity_re)
= map qr/$_/i,
join '|',
grep /;\z/,
sort keys %HTML::Entities::entity2char;
sub _fix_text_encoding {
my $text = shift;
$text =~ s{
&
(?:
($short_entity_re);?
|
($complete_entity_re)
)?
}{
defined $1 ? "&$1;"
: defined $2 ? "&$2"
: "&"
}xgie;
return encode_entities( $text, '<>' );
}
1; # End of HTML::Restrict
# ABSTRACT: Strip unwanted HTML tags and attributes
__END__
=pod
=encoding UTF-8
=head1 NAME
HTML::Restrict - Strip unwanted HTML tags and attributes
=head1 VERSION
version v3.0.2
=head1 SYNOPSIS
use HTML::Restrict;
my $hr = HTML::Restrict->new();
# use default rules to start with (strip away all HTML)
my $processed = $hr->process(' <b>i am bold</b> ');
# $processed now equals: 'i am bold'
# Now, a less restrictive example:
$hr = HTML::Restrict->new(
rules => {
b => [],
img => [qw( src alt / )]
}
);
my $html = q[<body><b>hello</b> <img src="pic.jpg" alt="me" id="test" /></body>];
$processed = $hr->process( $html );
# $processed now equals: <b>hello</b> <img src="pic.jpg" alt="me" />
=head1 DESCRIPTION
This module uses L<HTML::Parser> to strip HTML from text in a restrictive
manner. By default all HTML is restricted. You may alter the default
behaviour by supplying your own tag rules.
=head1 CONSTRUCTOR AND STARTUP
=head2 new()
Creates and returns a new HTML::Restrict object.
my $hr = HTML::Restrict->new()
HTML::Restrict doesn't require any params to be passed to new. If your goal is
to remove all HTML from text, then no further setup is required. Just pass
your text to the process() method and you're done:
my $plain_text = $hr->process( $html );
If you need to set up specific rules, have a look at the params which
HTML::Restrict recognizes:
=over 4
=item * C<< rules => \%rules >>
Sets the rules which will be used to process your data. By default all HTML
tags are off limits. Use this argument to define the HTML elements and
corresponding attributes you'd like to use. Essentially, consider the default
behaviour to be:
rules => {}
Rules should be passed as a HASHREF of allowed tags. Each hash value should
represent the allowed attributes for the listed tag. For example, if you want
to allow a fair amount of HTML, you can try something like this:
my %rules = (
a => [qw( href target )],
b => [],
caption => [],
center => [],
em => [],
i => [],
img => [qw( alt border height width src style )],
li => [],
ol => [],
p => [qw(style)],
span => [qw(style)],
strong => [],
sub => [],
sup => [],
table => [qw( style border cellspacing cellpadding align )],
tbody => [],
td => [],
tr => [],
u => [],
ul => [],
);
my $hr = HTML::Restrict->new( rules => \%rules )
Or, to allow only bolded text:
my $hr = HTML::Restrict->new( rules => { b => [] } );
Allow bolded text, images and some (but not all) image attributes:
my %rules = (
b => [ ],
img => [qw( src alt width height border / )
);
my $hr = HTML::Restrict->new( rules => \%rules );
Since L<HTML::Parser> treats a closing slash as an attribute, you'll need to
add "/" to your list of allowed attributes if you'd like your tags to retain
closing slashes. For example:
my $hr = HTML::Restrict->new( rules =>{ hr => [] } );
$hr->process( "<hr />"); # returns: <hr>
my $hr = HTML::Restrict->new( rules =>{ hr => [qw( / )] } );
$hr->process( "<hr />"); # returns: <hr />
HTML::Restrict strips away any tags and attributes which are not explicitly
allowed. It also rebuilds your explicitly allowed tags and places their
attributes in the order in which they appear in your rules.
So, if you define the following rules:
my %rules = (
...
img => [qw( src alt title width height id / )]
...
);
then your image tags will all be built like this:
<img src=".." alt="..." title="..." width="..." height="..." id=".." />
This gives you greater consistency in your tag layout. If you don't care about
element order you don't need to pay any attention to this, but you should be
aware that your elements are being reconstructed rather than just stripped
down.
As of 2.1.0, you can also specify a regex to be tested against the attribute
value. This feature should be considered experimental for the time being:
my $hr = HTML::Restrict->new(
rules => {
iframe => [
qw( width height allowfullscreen ),
{ src => qr{^http://www\.youtube\.com},
frameborder => qr{^(0|1)$},
}
],
img => [ qw( alt ), { src => qr{^/my/images/} }, ],
},
);
my $html = '<img src="http://www.example.com/image.jpg" alt="Alt Text">';
my $processed = $hr->process( $html );
# $processed now equals: <img alt="Alt Text">
As of 2.3.0, the value to be tested against can also be a code reference. The
code reference will be passed the value of the attribute, and should return
either a string to use for the attribute value, or undef to remove the attribute.
my $hr = HTML::Restrict->new(
rules => {
span => [
{ style => sub {
my $value = shift;
# all colors are orange
$value =~ s/\bcolor\s*:\s*[^;]+/color: orange/g;
return $value;
} }
],
},
);
my $html = '<span style="color: #0000ff;">This is blue</span>';
my $processed = $hr->process( $html );
# $processed now equals: <span style="color: orange;">
=item * C<< trim => [0|1] >>
By default all leading and trailing spaces will be removed when text is
processed. Set this value to 0 in order to disable this behaviour.
=item * C<< uri_schemes => [undef, 'http', 'https', 'irc', ... ] >>
As of version 1.0.3, URI scheme checking is performed on all href and src tag
attributes. The following schemes are allowed out of the box. No action is
required on your part:
[ undef, 'http', 'https' ]
(undef represents relative URIs). These restrictions have been put in place to
prevent XSS in the form of:
<a href="javascript:alert(document.cookie)">click for cookie!</a>
See L<URI> for more detailed info on scheme parsing. If, for example, you
wanted to filter out every scheme barring SSL, you would do it like this:
uri_schemes => ['https']
This feature is new in 1.0.3. Previous to this, there was no schema checking
at all. Moving forward, you'll need to whitelist explicitly all URI schemas
which are not supported by default. This is in keeping with the whitelisting
behaviour of this module and is also the safest possible approach. Keep in
mind that changes to uri_schemes are not additive, so you'll need to include
the defaults in any changes you make, should you wish to keep them:
# defaults + irc + mailto
uri_schemes => [ 'undef', 'http', 'https', 'irc', 'mailto' ]
=item * allow_declaration => [0|1]
Set this value to true if you'd like to allow/preserve DOCTYPE declarations in
your content. Useful when cleaning up your own static files or templates. This
feature is off by default.
my $html = q[<!doctype html><body>foo</body>];
my $hr = HTML::Restrict->new( allow_declaration => 1 );
$html = $hr->process( $html );
# $html is now: "<!doctype html>foo"
=item * allow_comments => [0|1]
Set this value to true if you'd like to allow/preserve HTML comments in your
content. Useful when cleaning up your own static files or templates. This
feature is off by default.
my $html = q[<body><!-- comments! -->foo</body>];
my $hr = HTML::Restrict->new( allow_comments => 1 );
$html = $hr->process( $html );
# $html is now: "<!-- comments! -->foo"
=item * create_newlines => [0|1]
Set the value to true if you'd like to have each br tag replaced by a
newline and every p tag replaced by two newlines. If a tag is
specified in the allowed HTML, it won't be replaced.
=item * replace_img => [0|1|CodeRef]
Set the value to true if you'd like to have img tags replaced with
C<[IMAGE: ...]> containing the alt attribute text. If you set it to a
code reference, you can provide your own replacement (which may
even contain HTML).
sub replacer {
my ($tagname, $attr, $text) = @_; # from HTML::Parser
return qq{<a href="$attr->{src}">IMAGE: $attr->{alt}</a>};
}
my $hr = HTML::Restrict->new( replace_img => \&replacer );
This attribute will only take effect if the img tag is not included
in the allowed HTML.
=item * strip_enclosed_content => [0|1]
The default behaviour up to 1.0.4 was to preserve the content between script
and style tags, even when the tags themselves were being deleted. So, you'd be
left with a bunch of JavaScript or CSS, just with the enclosing tags missing.
This is almost never what you want, so starting at 1.0.5 the default will be to
remove any script or style info which is enclosed in these tags, unless they
have specifically been whitelisted in the rules. This will be a sane default
when cleaning up content submitted via a web form. However, if you're using
HTML::Restrict to purge your own HTML you can be more restrictive.
# strip the head section, in addition to JS and CSS
my $html = '<html><head>...</head><body>...<script>JS here</script>foo';
my $hr = HTML::Restrict->new(
strip_enclosed_content => [ 'script', 'style', 'head' ]
);
$html = $hr->process( $html );
# $html is now '<html><body>...foo';
The caveat here is that HTML::Restrict will not try to fix broken HTML. In the
above example, if you have any opening script, style or head tags which don't
also include matching closing tags, all following content will be stripped
away, regardless of any parent tags.
Keep in mind that changes to strip_enclosed_content are not additive, so if you
are adding additional tags you'll need to include the entire list of tags whose
enclosed content you'd like to remove. This feature strips script and style
tags by default.
=item * C<< filter_text => [0|1|CodeRef] >>
By default all text will be filtered to fix any encoding problems which may
cause security issues. You may override the encoding behaviour by providing
your own anonymous sub to C<filter_text>. This first and only argument to the
sub is the text which needs to be filtered. The sub should return a scalar
containing the transformed text.
filter_text => sub {
my $text = shift;
... # transform text
return $text;
},
You may also this value to 0 in order to disable this behaviour entirely.
Please be advised this is a security risk. Use caution when disabling this
parameter or providing your own filter function.
=back
=head1 SUBROUTINES/METHODS
=head2 process( $html )
This is the method which does the real work. It parses your data, removes any
tags and attributes which are not specifically allowed and returns the
resulting text. Requires and returns a SCALAR.
=head2 get_rules
Accessor which returns a hash ref of the current rule set.
=head2 get_uri_schemes
Accessor which returns an array ref of the current valid uri schemes.
=head1 CAVEATS
Please note that all tag and attribute names passed via the rules param must be
supplied in lower case.
# correct
my $hr = HTML::Restrict->new( rules => { body => ['onload'] } );
# throws a fatal error
my $hr = HTML::Restrict->new( rules => { Body => ['onLoad'] } );
=head1 MOTIVATION
There are already several modules on the CPAN which accomplish much of the same
thing, but after doing a lot of poking around, I was unable to find a solution
with a simple setup which I was happy with.
The most common use case might be stripping HTML from user submitted data
completely or allowing just a few tags and attributes to be displayed. With
the exception of URI scheme checking, this module doesn't do any validation on
the actual content of the tags or attributes. If this is a requirement, you
can either mess with the parser object, post-process the text yourself or have
a look at one of the more feature-rich modules in the SEE ALSO section below.
My aim here is to keep things easy and, hopefully, cover a lot of the less
complex use cases with just a few lines of code and some brief documentation.
The idea is to be up and running quickly.
=head1 SEE ALSO
L<HTML::TagFilter>, L<HTML::Defang>, L<MojoMojo::Declaw>, L<HTML::StripScripts>,
L<HTML::Detoxifier>, HTML::Sanitizer, L<HTML::Scrubber>
=head1 ACKNOWLEDGEMENTS
Thanks to Raybec Communications L<http://www.raybec.com> for funding my
work on this module and for releasing it to the world.
Thanks also to the many other contributors. L<https://github.com/oalders/html-restrict/graphs/contributors>
=head1 AUTHOR
Olaf Alders <olaf@wundercounter.com>
=head1 COPYRIGHT AND LICENSE
This software is copyright (c) 2009 by Olaf Alders.
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
=cut
|