/
Acid.pm
535 lines (432 loc) · 14 KB
/
Acid.pm
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
package HTML::Acid;
use base HTML::Parser;
use warnings;
use strict;
use Carp;
use Readonly;
use HTML::Acid::Buffer;
use String::Dirify qw(dirify);
use version; our $VERSION = qv('0.0.1');
# Module implementation here
Readonly my %START_HANDLERS => (
img=>\&_img_start,
h1=>\&_h_start,
h2=>\&_h_start,
h3=>\&_h_start,
h4=>\&_h_start,
h5=>\&_h_start,
h6=>\&_h_start,
p=>\&_p_start,
a=>\&_a_start,
);
Readonly my %END_HANDLERS => (
h1=>\&_h_end,
h2=>\&_h_end,
h3=>\&_h_end,
h4=>\&_h_end,
h5=>\&_h_end,
h6=>\&_h_end,
p=>\&_p_end,
a=>\&_a_end,
);
Readonly my $URL_REGEX => qr{
\A # start of string
/ # internal URLs only by default
\w # at least one normal character
[\w\-/]* #
(?:\#[\w\-]+)? # optional anchor
\z # end of string
}xms;
Readonly my $ALT_REGEX => qr{
\A # start of string
[\w\s\.\,]+ #
\z # end of string
}xms;
sub new {
my $class = shift;
my %args = @_;
my $tag_hierarchy = $args{tag_hierarchy};
if (not $tag_hierarchy) {
$tag_hierarchy = $class->default_tag_hierarchy;
}
my $url_regex = $args{url_regex};
if (not $url_regex) {
$url_regex = $URL_REGEX;
}
# Configue HTML::Prser options
my $self = HTML::Parser->new(
api_version => 3,
empty_element_tags=>1,
strict_comment=>1,
attr_encoded=>1,
);
# Set up HTML::Parser handlers
$self->handler(text=>'_text_process', 'self,dtext');
$self->handler(start=>'_start_process', 'self,tagname,attr');
$self->handler(end=>'_end_process', 'self,tagname');
$self->handler(end_document=>'_end_document', 'self');
$self->handler(start_document=>'_reset', 'self');
# Bypass as much as possible
$self->ignore_elements('script','style');
my @tags = sort {
# sort like this so that the later depth calcs do not
# loop for ever.
$tag_hierarchy->{$a} cmp $tag_hierarchy->{$b}
} keys %$tag_hierarchy;
$self->report_tags(@tags, 'br');
# calculate depths
$self->{_acid_depths}->{''} = 0;
while(@tags) {
my $tag = shift @tags;
my $value = $tag_hierarchy->{$tag};
if (exists $self->{_acid_depths}->{$value}) {
$self->{_acid_depths}->{$tag}
= $self->{_acid_depths}->{$value} + 1;
}
else {
push @tags, $tag;
}
}
$self->{_acid_hierarchy} = $tag_hierarchy;
$self->{_acid_url_regex} = $url_regex;
bless $self, $class;
return $self;
}
sub _text_process {
my $self = shift;
my $dtext = shift;
my $text_nontrivial = $dtext =~ /\S/;
# New text clears a single <br> tag
if ($self->{_acid_br} and $text_nontrivial) {
$self->{_acid_br} = 0;
}
# To add to the buffer unhindered we must not be in the
# start state.
my $actual_state = $self->{_acid_state};
if ($actual_state eq '' and $text_nontrivial) {
$self->_start_process('p', {});
}
$self->_buffer($dtext);
return;
}
sub _start_process {
my $self = shift;
my $tagname = shift;
my $attr = shift;
my $actual_state = $self->{_acid_state};
# Two br tags in a row means 'new paragraph'.
if ($tagname eq 'br') {
return if $actual_state ne 'p';
if ($self->{_acid_br}) {
$self->{_acid_br} = 0;
$self->_end_process('p');
}
else {
$self->{_acid_br} = 1;
}
return;
}
$self->{_acid_br} = 0;
# To call _start_process unhindered
# the parent tag of $tagname must be the
# current state.
my $required_state = $self->{_acid_hierarchy}->{$tagname};
if ($required_state ne $actual_state) {
my $required_depth = $self->{_acid_depths}->{$required_state};
my $actual_depth = $self->{_acid_depths}->{$actual_state};
if ($actual_depth >= $required_depth) {
$self->_end_process($actual_state);
}
if ($required_state) {
$self->_start_process($required_state, {});
}
}
if (exists $START_HANDLERS{$tagname}) {
my $callback = $START_HANDLERS{$tagname};
$self->$callback($tagname,$attr);
}
else {
$self->_buffer("<$tagname>");
}
# State shifts to the current tag.
# The 'img' end tag does not get called in some cases.
$self->{_acid_state} = $tagname if $tagname ne 'img';
return;
}
sub _end_process {
my $self = shift;
my $tagname = shift;
return if $tagname eq 'br';
# To call _start_process unhindered
# $tagname must be the current state.
my $actual_state = $self->{_acid_state};
if ($tagname ne $actual_state) {
my $tag_depth = $self->{_acid_depths}->{$tagname};
my $actual_depth = $self->{_acid_depths}->{$actual_state};
return if $tag_depth >= $actual_depth;
$self->_end_process($actual_state);
}
if (exists $END_HANDLERS{$tagname}) {
my $callback = $END_HANDLERS{$tagname};
$self->$callback($tagname);
}
else {
$self->_buffer("</$tagname>");
}
# State shifts to the parent tag.
$self->{_acid_state} = $self->{_acid_hierarchy}->{$tagname};
return;
}
sub _end_document {
my $self = shift;
# We want to end in the start state.
my $actual_state = $self->{_acid_state};
if ($actual_state ne '') {
$self->_end_process('p');
$self->_buffer("\n");
}
return;
}
sub _img_start {
my $self = shift;
my $tagname = shift;
my $attr = shift;
return if not my $alt = $attr->{alt};
my $src = $self->_url($attr->{src});
if ($src and
my $height = $attr->{height} and
my $width = $attr->{width} and
my $title = $attr->{title}) {
$self->_buffer("<img alt=\"$alt\" height=\"$height\" src=\"$src\" "
."title=\"$title\" width=\"$width\" />");
}
elsif ($alt =~ $ALT_REGEX) {
$self->_buffer(" $alt ");
}
return;
}
sub _url {
my $self = shift;
my $url = shift;
return if not $url;
return if $url !~ $self->{_acid_url_regex};
return $url;
}
sub _a_start {
my $self = shift;
my $tagname = shift;
my $attr = shift;
my $buffer = HTML::Acid::Buffer->new($tagname);
$buffer->set_attr($attr);
unshift @{$self->{_acid_buffer}}, $buffer;
return;
}
sub _a_end {
my $self = shift;
my $tagname = shift;
my $buffer = shift @{$self->{_acid_buffer}};
my $attr = $buffer->get_attr;
my $text = $buffer->state;
return if not $text;
return if $text !~ /\S/;
my $href = $self->_url($attr->{href});
if (not $href) {
$self->_buffer(" $text ");
return;
}
my $new_attr = {href=>$href};
if ($attr->{title}) {
$new_attr->{title} = $attr->{title};
}
$buffer->set_attr($new_attr);
$self->_buffer($buffer->stop);
return;
}
sub _h_start {
my $self = shift;
my $tagname = shift;
my $attr = shift;
my $buffer = HTML::Acid::Buffer->new($tagname);
$buffer->set_attr($attr);
unshift @{$self->{_acid_buffer}}, $buffer;
return;
}
sub _h_end {
my $self = shift;
my $tagname = shift;
my $buffer = shift @{$self->{_acid_buffer}};
my $attr = $buffer->get_attr;
my $text = $buffer->state;
return if not $text;
my $id = exists $attr->{id} ? $attr->{id} : dirify($text,'-');
$buffer->set_attr({id=>$id});
$self->_buffer($buffer->stop);
return;
}
sub _p_start {
my $self = shift;
my $tagname = shift;
unshift @{$self->{_acid_buffer}}, HTML::Acid::Buffer->new($tagname);
return;
}
sub _p_end {
my $self = shift;
my $tagname = shift;
my $buffer = shift @{$self->{_acid_buffer}};
if ($buffer->state =~ /\S/) {
$self->_buffer($buffer->stop);
}
return;
}
sub _buffer {
my $self = shift;
my $text = shift;
$self->{_acid_buffer}->[0]->add($text);
return;
}
sub _reset {
my $self = shift;
$self->{_acid_buffer} = [HTML::Acid::Buffer->new];
$self->{_acid_state} = "";
$self->{_acid_br} = 0;
return;
}
sub burn {
my $self = shift;
my $text = shift;
$self->parse($text);
$self->eof;
return $self->{_acid_buffer}->[0]->stop;
}
sub default_tag_hierarchy {
return {
h3 => '',
p => '',
a => 'p',
img => 'p',
em => 'p',
strong => 'p',
};
}
1; # Magic true value required at end of module
__END__
=head1 NAME
HTML::Acid - Reformat HTML fragment to strict criteria
=head1 VERSION
This document describes HTML::Acid version 0.0.1
=head1 SYNOPSIS
use HTML::Acid;
my $acid = HTML::Acid->new;
return $acid->burn($html)
=head1 DESCRIPTION
Fragments of HTML returned by a rich text editor tend to be not entirely
standards compliant. C<img> tags tend not to be closed. Paragraphs breaks
might be represented by double C<br> tags rather than C<p> tags. Of course
we also need to do all the XSS avoidance an HTML clean up routine would,
such as controlling C<href> tags, removing javascript and inline styling.
Furthermore what one often wants is not simply a standards compliant cleaned
up version of the input HTML. Sometimes one wants to know that the HTML
conforms to a much tighter standard, as then it will be easier to style.
So this module, given a fragment of HTML, will rewrite it into a very
restricted subset of XHTML. The default dialect has the following properties.
=over
=item * Documents consist entirely of C<p> elements and
C<h3> elements.
=item * Every header will have C<id> attribute automatically generated
from the header contents.
=item * Every paragraph may consist of text, C<a> elements, C<img> elements,
C<strong> and C<em> elements.
=item * Anchors must have an C<href> attribute referring to an internal
URL. They may also have a C<title> attribute.
=item * Images must have C<src>, C<title>, C<alt>, C<height> and C<width>
attributes. The C<src> attribute must match the same regular expression
as C<href>. If any of these tags are missing the image is replaced by
the contents of the C<alt> attribute, so long as it consists only of
alphanumeric characters, spaces, full stops and commas. Otherwise the image
is removed.
=item * All other tags must have no attributes and may only contain text.
=item * Double C<br> elements in the source will be interpreted as paragraph
breaks.
=back
=head1 INTERFACE
=head2 new
This constructor takes two named parameters.
=over
=item I<url_regex>
This is a regular expression that controls what C<href> and C<src> tags
are permitted. It defaults to an expression that restricts access to internal
absolute paths with an optional sub-reference.
=item I<tag_hierarchy>
This is a hash reference that for each supported tag specifies what
the containing tag must be. Standards based HTML is not as strict as this.
This defaults to the value returned by the C<default_tag_hierarchy>
method.
=back
=head2 burn
This method takes the input HTML as an input and returns the cleaned
up HTML.
=head2 default_tag_hierarchy
This is a class method that returns the default tag hierarchy. So if
you want to add support for a tag you can use a modified copy of the
output when setting up the L<HTML::Acid> instance. The default
mapping is as follows:
{
h3 => '',
p => '',
a => 'p',
img => 'p',
em => 'p',
strong => 'p',
}
=head1 CONFIGURATION AND ENVIRONMENT
HTML::Acid requires no configuration files or environment variables.
=head1 DEPENDENCIES
This module works by subclassing L<HTML::Parser>.
=head1 INCOMPATIBILITIES
None reported.
=head1 TO DO
=over
=item * More relaxed treatment of the C<alt> tag would be good. However it is
easier to go from restrictive behaviour to more relaxed so it will stay like
it is for now.
=item * Sooner or later a little more flexibility in handling attributes
will be required.
=item * I think this module could do with an XS back-end for a speed up.
=back
=head1 BUGS AND LIMITATIONS
No bugs have been reported.
Please report any bugs or feature requests to
C<bug-html-acid@rt.cpan.org>, or through the web interface at
L<http://rt.cpan.org>.
=head1 SEE ALSO
There are many other modules that do something similar. Of those I think
the most complete is L<HTML::StriptScripts::Parser>. You can also see
L<HTML::Declaw>, L<HTML::Clean>, L<HTML::Defang>, L<HTML::Restrict>,
L<HTML::Scrubber>, L<HTML::Laundary>, L<HTML::Detoxifier>, L<Marpa::HTML>,
L<HTML::Tidy>. People also often refer to HTML::Santitizer.
=head1 AUTHOR
Nicholas Bamber C<< <nicholas@periapt.co.uk> >>
=head1 LICENCE AND COPYRIGHT
Copyright (c) 2010, Nicholas Bamber C<< <nicholas@periapt.co.uk> >>. All rights reserved.
This module is free software; you can redistribute it and/or
modify it under the same terms as Perl itself. See L<perlartistic>.
=head1 DISCLAIMER OF WARRANTY
BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
NECESSARY SERVICING, REPAIR, OR CORRECTION.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.