blib/lib/HTML/Defang.pm

filter: Statementstmt 94.0% 727 / 773 Branchbran 74.3% 422 / 568 Conditioncond 62.7% 199 / 317 MC/DCmcdc 44.8% 79 / 176 Subroutinesub 96.3% 52 / 54 Podpod 50.0% 17 / 34 totaltotal 77.8% 1496 / 1922 CC 411 SCAR 36.3
CC
411
Cov
81%
get_applicable_charset
90.0
defang
74.5
cleanup_style
67.7
CRAP 37.8
↑ Summary
1 package HTML::Defang;
2  
3 =head1 NAME
4  
5 HTML::Defang - Cleans HTML as well as CSS of scripting and other executable contents, and neutralises XSS attacks.
6  
7 =head1 SYNOPSIS
8  
9 my $InputHtml = "<html><body></body></html>";
10  
11 my $Defang = HTML::Defang->new(
12 context => $Self,
13 fix_mismatched_tags => 1,
14 tags_to_callback => [ br embed img ],
15 tags_callback => \&DefangTagsCallback,
16 url_callback => \&DefangUrlCallback,
17 css_callback => \&DefangCssCallback,
18 attribs_to_callback => [ qw(border src) ],
19 attribs_callback => \&DefangAttribsCallback,
20 content_callback => \&ContentCallback,
21 );
22  
23 my $SanitizedHtml = $Defang->defang($InputHtml);
24  
25 # Callback for custom handling specific HTML tags
26 sub DefangTagsCallback {
27 my ($Self, $Defang, $OpenAngle, $lcTag, $IsEndTag, $AttributeHash, $CloseAngle, $HtmlR, $OutR) = @_;
28  
29 # Explicitly defang this tag, eventhough safe
30 return DEFANG_ALWAYS if $lcTag eq 'br';
31  
32 # Explicitly whitelist this tag, eventhough unsafe
33 return DEFANG_NONE if $lcTag eq 'embed';
34  
35 # I am not sure what to do with this tag, so process as HTML::Defang normally would
36 return DEFANG_DEFAULT if $lcTag eq 'img';
37 }
38  
39 # Callback for custom handling URLs in HTML attributes as well as style tag/attribute declarations
40 sub DefangUrlCallback {
41 my ($Self, $Defang, $lcTag, $lcAttrKey, $AttrValR, $AttributeHash, $HtmlR) = @_;
42  
43 # Explicitly allow this URL in tag attributes or stylesheets
44 return DEFANG_NONE if $$AttrValR =~ /safesite.com/i;
45  
46 # Explicitly defang this URL in tag attributes or stylesheets
47 return DEFANG_ALWAYS if $$AttrValR =~ /evilsite.com/i;
48 }
49  
50 # Callback for custom handling style tags/attributes
51 sub DefangCssCallback {
52 my ($Self, $Defang, $Selectors, $SelectorRules, $Tag, $IsAttr) = @_;
53 my $i = 0;
54 foreach (@$Selectors) {
55 my $SelectorRule = $$SelectorRules[$i];
56 foreach my $KeyValueRules (@$SelectorRule) {
57 foreach my $KeyValueRule (@$KeyValueRules) {
58 my ($Key, $Value) = @$KeyValueRule;
59  
60 # Comment out any '!important' directive
61 $$KeyValueRule[2] = DEFANG_ALWAYS if $Value =~ '!important';
62  
63 # Comment out any 'position=fixed;' declaration
64 $$KeyValueRule[2] = DEFANG_ALWAYS if $Key =~ 'position' && $Value =~ 'fixed';
65 }
66 }
67 $i++;
68 }
69 }
70  
71 # Callback for custom handling HTML tag attributes
72 sub DefangAttribsCallback {
73 my ($Self, $Defang, $lcTag, $lcAttrKey, $AttrValR, $HtmlR) = @_;
74  
75 # Change all 'border' attribute values to zero.
76 $$AttrValR = '0' if $lcAttrKey eq 'border';
77  
78 # Defang all 'src' attributes
79 return DEFANG_ALWAYS if $lcAttrKey eq 'src';
80  
81 return DEFANG_NONE;
82 }
83  
84 # Callback for all content between tags (except <style>, <script>, etc)
85 sub DefangContentCallback {
86 my ($Self, $Defang, $ContentR) = @_;
87  
88 $$ContentR =~ s/remove this content//;
89 }
90  
91 =head1 DESCRIPTION
92  
93 This module accepts an input HTML and/or CSS string and removes any executable code including scripting, embedded objects, applets, etc., and neutralises any XSS attacks. A whitelist based approach is used which means only HTML known to be safe is allowed through.
94  
95 HTML::Defang uses a custom html tag parser. The parser has been designed and tested to work with nasty real world html and to try and emulate as close as possible what browsers actually do with strange looking constructs. The test suite has been built based on examples from a range of sources such as http://ha.ckers.org/xss.html and http://imfo.ru/csstest/css_hacks/import.php to ensure that as many as possible XSS attack scenarios have been dealt with.
96  
97 HTML::Defang can make callbacks to client code when it encounters the following:
98  
99 =over 4
100  
101 =item *
102  
103 When a specified tag is parsed
104  
105 =item *
106  
107 When a specified attribute is parsed
108  
109 =item *
110  
111 When a URL is parsed as part of an HTML attribute, or CSS property value.
112  
113 =item *
114  
115 When style data is parsed, as part of an HTML style attribute, or as part of an HTML <style> tag.
116  
117 =back
118  
119 The callbacks include details about the current tag/attribute that is being parsed, and also gives a scalar reference to the input HTML. Querying pos() on the input HTML should indicate where the module is with parsing. This gives the client code flexibility in working with HTML::Defang.
120  
121 HTML::Defang can defang whole tags, any attribute in a tag, any URL that appear as an attribute or style property, or any CSS declaration in a declaration block in a style rule. This helps to precisely block the most specific unwanted elements in the contents(for example, block just an offending attribute instead of the whole tag), while retaining any safe HTML/CSS.
122  
123 =cut
124  
125 11 ▶use Exporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
126 11 our @ISA = ('Exporter');
127 11 %EXPORT_TAGS = (all => [qw(@FormTags DEFANG_NONE DEFANG_ALWAYS DEFANG_DEFAULT)]);
128 11 Exporter::export_ok_tags('all');
129  
130 11 ▶use 5.008;
Subroutine BEGIN: called CC=1 SCAR=0.0
131 11 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
132 11 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
133  
134 11 our $VERSION='1.10';
135  
136 11 ▶use constant DEFANG_NONE => 0;
Subroutine BEGIN: called CC=1 SCAR=0.0
137 11 ▶use constant DEFANG_ALWAYS => 1;
Subroutine BEGIN: called CC=1 SCAR=0.0
138 11 ▶use constant DEFANG_DEFAULT => 2;
Subroutine BEGIN: called CC=1 SCAR=0.0
139  
140 11 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
141 11 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
142  
143 11 my $HasScalarReadonly = 0;
144 0 ▶BEGIN { eval "use Scalar::Readonly qw(readonly_on);" && ($HasScalarReadonly = 1); }
Subroutine BEGIN: called CC=2 SCAR=9.2
Subroutine BEGIN: called CC=1 SCAR=1.2
Branch: 1 branch
BranchTrueFalseTotal
eval "use Scalar::Readonly qw(readonly_on);" and $HasScalarReadonly = 1 0 11 11
145  
146 11 our @FormTags = qw(form input textarea select option button fieldset label legend multicol nextid optgroup);
147  
148 # Some regexps for matching HTML tags + key=value attributes
149 11 my $AttrKeyStartLineRE = qr/(?:[^=<>\s\/\\]{1,}|[\/](?!\s*>))/;
150 11 my $AttrKeyRE = qr/(?<=[\s'"\/])$AttrKeyStartLineRE/;
151 11 my $AttrValRE = qr/[^>\s'"`][^>\s]*|'[^']*?'|"[^"]*?"|`[^`]*?`/;
152 11 my $AttributesRE = qr/(?:(?:$AttrKeyRE\s*)?(?:=\s*$AttrValRE\s*)?)*/;
153 11 my $TagNameRE = qr/[A-Za-z][A-Za-z0-9\#\&\;\:\!_-]*/;
154  
155 11 my $StyleSelectors = qr/[^{}\s][^{}]{0,1024}?/;
156 11 my $StyleName = qr/[^:}\s][^:{}]*?/;
157 11 my $StyleValue = qr/[^;}\s][^;}]*|.*$/;
158 11 my $StyleRule = qr/$StyleName\s*:\s*$StyleValue\s*/;
159 11 my $StyleRules = qr/\s*(?:$StyleRule)?(?:;\s*$StyleRule)*(?:;\s*)*/;
160 11 my $StyleMediaSelector = qr/\@media\b[^{]*/;
161 11 my $RECStyleMediaSelector = qr{\G(\s*)($StyleMediaSelector)(\{)(\s*)}so;
162 11 my $RECStyleNaked = qr/\G(\s*)()()()($StyleRules)()(\s*)/o;
163 11 my $RECStyleSelected = qr/\G(\s*)((?:$StyleSelectors)?)(\s*)(\{)($StyleRules)(\})(\s*)/o;
164  
165 11 my $Fonts = qr/["']?([A-Za-z0-9\s-]+)["']?/;
166 11 my $Alignments = qr/(absbottom|absmiddle|all|autocentre|baseline|bottom|center|justify|left|middle|none|right|texttop|top)/;
167  
168 11 my $Executables = '([^@]\.com|'.
169 '.*\.(exe|cmd|bat|pif|scr|sys|sct|lnk|dll'.
170 '|vbs?|vbe|hta|shb|shs|hlp|chm|eml|wsf|wsh|js'.
171 '|asx|wm.|mdb|mht|msi|msp|cpl|lib|reg))';
172 11 my $SrcBanStd = qr/^([A-Za-z]*script|.*\&\{|mocha|about|opera|mailto:|hcp:|\/(dev|proc)|\\|file|smb|cid:${Executables}(@|\?|$))/i;
173  
174 11 my %Rules =
175 (
176 # Disallow unknown tags by default
177 "_unknown" => qr/.*/,
178 "align" => qr/^${Alignments}$/i,
179 "alnum" => qr/^[A-Za-z0-9_.-]+$/,
180 "boolean" => qr/^(0|1|true|yes|no|false)$/,
181 "charset" => qr/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/,
182 "class" => qr/^[A-Za-z0-9_.:\s-]*$/,
183 "color" => qr/^#?[0-9A-Z]+$/i,
184 "coords" => qr/^(\d+,)+\d+$/i,
185 "datetime" => qr/^\d\d\d\d-\d\d-\d\d.{0,5}\d\d:\d\d:\d\d.{0,5}$/,
186 "dir" => qr/^(ltr|rtl)$/i,
187 "empty" => qr/^$/i,
188 "eudora" => qr/^(autourl)$/i,
189 "font-face" => qr/^((${Fonts})[,\s]*)+$/i,
190 "form-enctype" => qr/^(application\/x-www-form-urlencoded|multipart\/form-data)$/i,
191 "form-method" => qr/^(get|post)$/i,
192 "frame" => qr/^(void|above|below|hsides|vsides|lhs|rhs|box|border)$/i,
193 # href: Not javascript, vbs or vbscript
194 "href" => [ qr/^((?:[a-z]*script|mocha|opera|about|data|tcl)\s*:|.*\&\{|hcp|smb|\/dev\/|<)/i ],
195 "usemap-href" => qr/^#[A-Za-z0-9_.-]+$/, # this is not really a href at all!
196 "input-size" => qr/^(\d{1,4})$/, # some browsers freak out with very large widgets
197 "input-type" => qr/^(button|checkbox|file|hidden|image|password|radio|readonly|reset|submit|text)$/i,
198 "integer" => qr/^(-|\+)?\d+$/,
199 "number" => qr/^(-|\+)?[\d.,]+$/,
200 # language: Not javascript, vbs or vbscript
201 "language" => qr/^(XML)$/i,
202 "media" => qr/^((screen|print|projection|braille|speech|all)[,\s]*)+$/i,
203 "meta:name" => qr/^(author|progid|originator|generator|keywords|description|content-type|pragma|expires)$/i,
204 # mime-type: Not javascript
205 "mime-type" => qr/^(cite|text\/(plain|css|html|xml))$/i,
206 "list-type" => qr/^(none,a,i,upper-alpha,lower-alpha,upper-roman,lower-roman,decimal,disc,square,circle,round)$/i,
207 # "rel" => qr/^((copyright|author|stylesheet)\s*)+$/i,
208 "rel" => qr/^((copyright|author)\s*)+$/i, # XXX external stylesheets can contain scripting, so kill them
209 "rules" => qr/^(none|groups|rows|cols|all)$/i,
210 "scope" => qr/^(row|col|rowgroup|colgroup)$/i,
211 "shape" => qr/^(rect|rectangle|circ|circle|poly|polygon)$/i,
212 # The following two are for URLs we expect to be auto-loaded by the browser,
213 # because they are within a frame, image or something like that.
214 # "src" => qr/^([a-z]+):|^[\w\.\/\%]+$/i,
215 "src" => qr/^https?:\/\/|^[\w.\/%]+$/i,
216 # "style" => qr/^([A-Za-z0-9_-]+\\s*:\\s*(yes|no)|text-align\\s*:\\s*$alignments|((background|(background-|font-)?color)\\s*:\\s*(\\#?[A-Z0-9]+)?|((margin|padding|border)-(right|left)|tab-interval|height|width)\\s*:\\s*[\\d\\.]+(pt|px)|font(-family|-size|-weight|)\\s*:(\\s*[\\d\\.]+(pt|px)|\\s*$fonts)+)[;\\s]*)+\$/i,
217 # "style" => qr/expression|eval|script:|mocha:|\&{|\@import|(?<!background-)position:|background-image/i, # XXX there are probably a million more ways to cause trouble with css!
218 "style" => qr/^.*$/s,
219 #kc In addition to this, we could strip all 'javascript:|expression|' etc. from all attributes(in attribute_cleanup())
220 "stylesheet" => [ qr/expression|eval|script:|mocha:|\&\{|\@import/i ], # stylesheets are forbidden if Embedded => 1. css positioning can be allowed in an iframe.
221 # NB see also `process_stylesheet' below
222 "style-type" => [ qr/script|mocha/i ],
223 "size" => qr/^[\+\-]?[\d.]+(px|%)?$/i,
224 "target" => qr/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/,
225 "base-href" => qr/^https?:\/\/[\w.\/]+$/,
226 "anything" => qr/^.*$/, #[ 0, 0 ],
227 "meta:content" => [ qr// ],
228 );
229  
230 11 my %CommonAttributes =
231 (
232 # Core attributes
233 "class" => "class",
234 "id" => "alnum",
235 "name" => "alnum",
236 "style" => "style",
237 "accesskey" => "alnum",
238 "tabindex" => "integer",
239 "title" => "anything",
240 # Language attributes
241 "dir" => "dir",
242 "lang" => "alnum",
243 "language" => "language",
244 "longdesc" => "anything",
245 # Height, width, alignment, etc.
246 "align" => "align",
247 "bgcolor" => "color",
248 "bottommargin" => "size",
249 "clear" => "align",
250 "color" => "color",
251 "height" => "size",
252 "leftmargin" => "size",
253 "marginheight" => "size",
254 "marginwidth" => "size",
255 "nowrap" => "anything",
256 "rightmargin" => "size",
257 "scroll" => "boolean",
258 "scrolling" => "boolean",
259 "topmargin" => "size",
260 "type" => "mime-type",
261 "valign" => "align",
262 "width" => "size",
263 "/" => "empty",
264 );
265  
266 11 my %ListAttributes =
267 (
268 "compact" => "anything",
269 "start" => "integer",
270 "type" => "list-type",
271 );
272  
273 11 my %TableAttributes =
274 (
275 "axis" => "alnum",
276 "background" => "src",
277 "border" => "number",
278 "bordercolor" => "color",
279 "bordercolordark" => "color",
280 "bordercolorlight" => "color",
281 "padding" => "integer",
282 "spacing" => "integer",
283 "cellpadding" => "integer",
284 "cellspacing" => "integer",
285 "cols" => "anything",
286 "colspan" => "integer",
287 "char" => "alnum",
288 "charoff" => "integer",
289 "datapagesize" => "integer",
290 "frame" => "frame",
291 "frameborder" => "boolean",
292 "framespacing" => "integer",
293 "headers" => "anything",
294 "rows" => "anything",
295 "rowspan" => "size",
296 "rules" => "rules",
297 "scope" => "scope",
298 "span" => "integer",
299 "summary" => "anything"
300 );
301  
302 11 my %UrlRules = (
303 "src" => 1,
304 "href" => 1,
305 "base-href" => 1,
306 # cite => 1,
307 # action => 1,
308 );
309  
310 11 my %Tags = (
311 script => \&defang_script_tag,
312 style => \&defang_style_tag,
313 "html" => 100,
314 #
315 # Safe elements commonly found in the <head> block follow.
316 #
317 "head" => 2,
318 "base" =>
319 {
320 "href" => "base-href",
321 "target" => "target",
322 },
323 # TODO: Deal with link below later
324 #"link" => \$r_link,
325 # {
326 # "rel" => "rel",
327 # "rev" => "rel",
328 # "src" => "src",
329 # "href" => "src", # Might be auto-loaded by the browser!!
330 # "charset" => "charset",
331 # "media" => "media",
332 # "target" => "target",
333 # "type" => "mime-type",
334 # },
335 "meta" =>
336 {
337 "_score" => 2,
338 "content" => "meta:content",
339 "http-equiv" => "meta:name",
340 "name" => "meta:name",
341 "charset" => "charset",
342 },
343 "title" => 2,
344 #
345 # Safe elements commonly found in the <body> block follow.
346 #
347 "body" =>
348 {
349 "_score" => 2,
350 "link" => "color",
351 "alink" => "color",
352 "vlink" => "color",
353 "background" => "src",
354 "nowrap" => "boolean",
355 "text" => "color",
356 "vlink" => "color",
357 },
358 "a" =>
359 {
360 "charset" => "charset",
361 "coords" => "coords",
362 "href" => "href",
363 "shape" => "shape",
364 "target" => "target",
365 "type" => "mime-type",
366 "eudora" => "eudora",
367 "notrack" => "anything",
368 },
369 "address" => 1,
370 "area" =>
371 {
372 "alt" => "anything",
373 "coords" => "coords",
374 "href" => "href",
375 "nohref" => "anything",
376 "shape" => "shape",
377 "target" => "target",
378 },
379 "article" => 1,
380 "applet" => 0,
381 "basefont" =>
382 {
383 "face" => "font-face",
384 "family" => "font-face",
385 "back" => "color",
386 "size" => "number",
387 "ptsize" => "number",
388 },
389 "bdo" => 1,
390 "bgsound" =>
391 {
392 "balance" => "integer",
393 "delay" => "integer",
394 "loop" => "alnum",
395 "src" => "src",
396 "volume" => "integer",
397 },
398 "blockquote" =>
399 {
400 "cite" => "href",
401 "type" => "mime-type",
402 },
403 "br" => 1,
404 "button" => # FORM
405 {
406 "type" => "input-type",
407 "disabled" => "anything",
408 "value" => "anything",
409 "tabindex" => "number",
410 },
411 "caption" => 1,
412 "center" => 1,
413 "col" => \%TableAttributes,
414 "colgroup" => \%TableAttributes,
415 "comment" => 1,
416 "dd" => 1,
417 "del" =>
418 {
419 "cite" => "href",
420 "datetime" => "datetime",
421 },
422 "dir" => \%ListAttributes,
423 "div" => 1,
424 "dl" => \%ListAttributes,
425 "dt" => 1,
426 "embed" => 0,
427 "fieldset" => 1, # FORM
428 "font" =>
429 {
430 "face" => "font-face",
431 "family" => "font-face",
432 "back" => "color",
433 "size" => "number",
434 "ptsize" => "number",
435 },
436 "footer" => 1,
437 "form" => # FORM
438 {
439 "method" => "form-method",
440 "action" => "href",
441 "enctype" => "form-enctype",
442 "accept" => "anything",
443 "accept-charset" => "anything",
444 },
445 "header" => 1,
446 "hr" =>
447 {
448 "size" => "number",
449 "noshade" => "anything",
450 },
451 "h1" => 1,
452 "h2" => 1,
453 "h3" => 1,
454 "h4" => 1,
455 "h5" => 1,
456 "h6" => 1,
457 "iframe" => 0,
458 "ilayer" => 0,
459 "img" =>
460 {
461 "alt" => "anything",
462 "border" => "size",
463 "dynsrc" => "src",
464 "hspace" => "size",
465 "ismap" => "anything",
466 "loop" => "alnum",
467 "lowsrc" => "src",
468 "nosend" => "alnum",
469 "src" => "src",
470 "start" => "alnum",
471 "usemap" => "usemap-href",
472 "vspace" => "size",
473 },
474 "inlineinput" => 0,
475 "input" => # FORM
476 {
477 "type" => "input-type",
478 "disabled" => "anything",
479 "value" => "anything",
480 "maxlength" => "input-size",
481 "size" => "input-size",
482 "readonly" => "anything",
483 "tabindex" => "number",
484 "checked" => "anything",
485 "accept" => "anything",
486 # for type "image":
487 "alt" => "anything",
488 "border" => "size",
489 "dynsrc" => "src",
490 "hspace" => "size",
491 "ismap" => "anything",
492 "loop" => "alnum",
493 "lowsrc" => "src",
494 "nosend" => "alnum",
495 "src" => "src",
496 "start" => "alnum",
497 "usemap" => "usemap-href",
498 "vspace" => "size",
499 },
500 "ins" =>
501 {
502 "cite" => "href",
503 "datetime" => "datetime",
504 },
505 "isindex" => 0,
506 "keygen" => 0,
507 "label" => # FORM
508 {
509 "for" => "alnum",
510 },
511 "layer" => 0,
512 "legend" => 1, # FORM
513 "li" => {
514 "value" => "integer",
515 },
516 "listing" => 0,
517 "map" => 1,
518 "marquee" => 0,
519 "menu" => \%ListAttributes,
520 "multicol" => 0,
521 "nextid" => 0,
522 "nobr" => 0,
523 "noembed" => 1,
524 "nolayer" => 1,
525 # Pretend our defang result is going into a non-scripting environment,
526 # even though javascript is likely enabled, so just defang all noscript tags
527 "noscript" => 0,
528 "noembed" => 1,
529 "object" => 0,
530 "ol" => \%ListAttributes,
531 "optgroup" => # FORM
532 {
533 "disabled" => "anything",
534 "label" => "anything",
535 },
536 "option" => # FORM
537 {
538 "disabled" => "anything",
539 "label" => "anything",
540 "selected" => "anything",
541 "value" => "anything",
542 },
543 "o:p" => 1,
544 "p" => 1,
545 "param" => 0,
546 "plaintext"=> 0,
547 "pre" => 1,
548 "rt" => 0,
549 "ruby" => 0,
550 "section" => 1,
551 "select" => # FORM
552 {
553 "disabled" => "anything",
554 "multiple" => "anything",
555 "size" => "input-size",
556 "tabindex" => "number",
557 },
558 "spacer" => 0,
559 "span" => 1,
560 "spell" => 0,
561 "sound" =>
562 {
563 "delay" => "number",
564 "loop" => "integer",
565 "src" => "src",
566 },
567 "table" => \%TableAttributes,
568 "tbody" => \%TableAttributes,
569 "textarea" => # FORM
570 {
571 "cols" => "input-size",
572 "rows" => "input-size",
573 "disabled" => "anything",
574 "readonly" => "anything",
575 "tabindex" => "number",
576 "wrap" => "anything",
577 },
578 "td" => \%TableAttributes,
579 "tfoot" => \%TableAttributes,
580 "th" => \%TableAttributes,
581 "thead" => \%TableAttributes,
582 "tr" => \%TableAttributes,
583 "ul" => \%ListAttributes,
584 "wbr" => 1,
585 "xml" => 0,
586 "xmp" => 0,
587 "x-html" => 0,
588 "x-tab" => 1,
589 "x-sigsep" => 1,
590 # Character formatting
591 "abbr" => 1,
592 "acronym"=> 1,
593 "big" => 1,
594 "blink" => 0,
595 "b" => 1,
596 "cite" => 1,
597 "code" => 1,
598 "dfn" => 1,
599 "em" => 1,
600 "i" => 1,
601 "kbd" => 1,
602 "q" => 1,
603 "s" => 1,
604 "samp" => 1,
605 "small" => 1,
606 "strike" => 1,
607 "strong" => 1,
608 "sub" => 1,
609 "sup" => 1,
610 "tt" => 1,
611 "u" => 1,
612 "var" => 1,
613 #
614 # Safe elements commonly found in the <frameset> block follow.
615 #
616 "frameset" => 0,
617 "frame" => 0,
618 "noframes" => 1,
619 );
620  
621 11 my %MathMLTags = (
622 mi => 1,
623 mn => 1,
624 mo => 1,
625 mtext => 1,
626 mspace => 1,
627 ms => 1,
628 mglyph => 1,
629 mrow => 1,
630 mfrac => 1,
631 msqrt => 1,
632 mroot => 1,
633 mstyle => 1,
634 merror => 1,
635 mpadded => 1,
636 mphantom => 1,
637 mfenced => 1,
638 menclose => 1,
639 msub => 1,
640 msup => 1,
641 msubsup => 1,
642 munder => 1,
643 mover => 1,
644 munderover => 1,
645 mmultiscripts => 1,
646 mtable => 1,
647 mtr => 1,
648 mtd => 1,
649 maligngroup => 1,
650 malignmark => 1,
651 mlabeledtr => 1,
652 maction => 1,
653 );
654  
655 # Some entity conversions for attributes
656 11 my $CtrlChars = qr/[\x00-\x08\x0b-\x1f]/;
657 11 my %EntityToChar = (quot => '"', apos => "'", amp => '&', 'lt' => '<', 'gt' => '>');
658 11 my %CharToEntity = ((reverse %EntityToChar), ' ' => '#x20', '/' => '#x2f', "\x09" => '#x09', "\x0a" => '#x0a');
659 11 my %QuoteRe = ('"' => qr/(["&<>\x09\x0a])/, "'" => qr/(['&<>\x09\x0a])/, "" => qr/(['"&<> \/\x09\x0a])/);
660  
661 # When fixing mismatched tags, sometimes a close tag
662 # shouldn't close all the way out
663 # For example, consider:
664 # <table><tr><td><table><tr></td>
665 # A naive version would see the ending </td>, and thus
666 # try to fix the mismatched tags by doing:
667 # <table><tr><td><table><tr></tr></table></td>
668 # This is not what a browser does. So given a tag, we
669 # give a list of closing tags which cause us to stop
670 # and not close any more
671 11 my %MismatchedTagNest = (
672 table => [ qw(tbody thead tfoot tr th td caption colgroup col) ],
673 tbody => [ qw(tr th td) ],
674 tr => [ qw(th td) ],
675 font => [ '' ],
676 );
677 # Convert to hash of hashes
678 11 $_ = { map { $_ => 1 } @$_ } for values %MismatchedTagNest;
679  
680 # If we see a table, we should expect to see a tbody
681 # next. If not, we need to add it because the browser
682 # will implicitly open it!
683 # For each tag, give list of tags that should follow. If
684 # we don't find one of them following, we open a new
685 # implicit tag of the first one in the list
686 # eg. <table><td> -> <table><tr><td>
687 11 my %ImplicitOpenTags = (
688 table => [ qw(tr tbody thead tfoot caption colgroup col) ],
689 thead => [ qw(tr) ],
690 tbody => [ qw(tr) ],
691 tr => [ qw(td th) ],
692 );
693 # Convert to hash of hashes
694 11 $_ = { default => $_->[0], map { $_ => 1 } @$_ } for values %ImplicitOpenTags;
695  
696 11 my %TableTags = map { $_ => 1 } qw(table tbody thead tfoot tr td th caption colgroup col);
697 11 my %BlockTags = map { $_ => 1 } qw(h1 h2 h3 h4 h5 h6 p div pre plaintext address blockquote center form table tbody thead tfoot tr td th caption colgroup col dl ul ol li fieldset);
698 11 my %InlineTags = map { $_ => 1 } qw(span abbr acronym q sub sup cite code em kbd samp strong var dfn strike b i u s tt small big nobr a font);
699 11 my %NestInlineTags = map { $_ => 1 } qw(span abbr acronym q sub sup cite code em kbd samp strong var dfn strike b i u s tt small big nobr);
700  
701 # Default list of mismatched tags to track
702 11 my %MismatchedTags = (%BlockTags, %InlineTags);
703  
704 # Elements whose contents are RCDATA (title, textarea) or RAWTEXT (noembed,
705 # noframes): the browser does not parse comments or nested tags inside them,
706 # only a matching end tag. We must consume their content as opaque text
707 # rather than parsing it as HTML, or an attacker can smuggle a literal end
708 # tag + active markup past us. See defang_rcdata_content(). (<script>,
709 # <style> and the defanged raw-text tags like <xmp>/<iframe> are handled
710 # separately.)
711 11 my %RawTextTags = map { $_ => 1 } qw(title textarea noembed noframes);
712  
713 =head1 CONSTRUCTOR
714  
715 =over 4
716  
717 =cut
718  
719 =item I<HTML::Defang-E<gt>new(%Options)>
720  
721 Constructs a new HTML::Defang object. The following options are supported:
722  
723 =over 4
724  
725 =item B<Options>
726  
727 =over 4
728  
729 =item B<tags_to_callback>
730  
731 Array reference of tags for which a call back should be made. If a tag in this array is parsed, the subroutine tags_callback() is invoked.
732  
733 =item B<attribs_to_callback>
734  
735 Array reference of tag attributes for which a call back should be made. If an attribute in this array is parsed, the subroutine attribs_callback() is invoked.
736  
737 =item B<tags_callback>
738  
739 Subroutine reference to be invoked when a tag listed in @$tags_to_callback is parsed.
740  
741 =item B<attribs_callback>
742  
743 Subroutine reference to be invoked when an attribute listed in @$attribs_to_callback is parsed.
744  
745 =item B<url_callback>
746  
747 Subroutine reference to be invoked when a URL is detected in an HTML tag attribute or a CSS property.
748  
749 =item B<css_callback>
750  
751 Subroutine reference to be invoked when CSS data is found either as the contents of a 'style' attribute in an HTML tag, or as the contents of a <style> HTML tag.
752  
753 =item B<content_callback>
754  
755 Subroutine reference to be invoked when standard content between HTML tags in found.
756  
757 =item B<fix_mismatched_tags>
758  
759 This property, if set, fixes mismatched tags in the HTML input. By default, tags present in the default %mismatched_tags_to_fix hash are fixed. This set of tags can be overridden by passing in an array reference $mismatched_tags_to_fix to the constructor. Any opened tags in the set are automatically closed if no corresponding closing tag is found. If an unbalanced closing tag is found, that is commented out.
760  
761 =item B<mismatched_tags_to_fix>
762  
763 Array reference of tags for which the code would check for matching opening and closing tags. See the property $fix_mismatched_tags.
764  
765 =item B<context>
766  
767 You can pass an arbitrary scalar as a 'context' value that's then passed as the first parameter to all callback functions. Most commonly this is something like '$Self'
768  
769 =item B<allow_double_defang>
770  
771 If this is true, then tag names and attribute names which already begin
772 with the defang string ("defang_" by default) will have an additional
773 copy of the defang string prepended if they are flagged to be defanged
774 by the return value of a callback, or if the tag or attribute name
775 is unknown.
776  
777 The default is to assume that tag names and attribute names beginning
778 with the defang string are already made safe, and need no further
779 modification, even if they are flagged to be defanged by the
780 return value of a callback. Any tag or attribute modifications made
781 directly by a callback are still performed.
782  
783 =item B<extract_styles>
784  
785 If set, C<< <style> >> elements are removed from the output, and their
786 defanged contents collected, to be fetched with C<extracted_styles> after
787 each call to C<defang>. A C<media> attribute on the element becomes an
788 C<@media> block around its contents. Use this to move a document's styles
789 somewhere else, such as into the C<< <head> >> of the page it's embedded in.
790  
791 =item B<scope_id>
792  
793 An id for an element the output will be put inside, such as C<'qt'>, to
794 keep the output's styles from applying to anything else in the page. Every
795 selector in a C<< <style> >> is put under C<#qt>, with a leading C<html>,
796 C<body> or C<:root> standing for that element itself; ids and classes in
797 selectors and markup get a C<qt-> prefix to match each other; and so do
798 C<name>s on C<< <a> >> and C<< <map> >> and the C<#> links to them. The
799 caller must add the element with that id. Usually used with
800 B<extract_styles>.
801  
802 =item B<url_policy>
803  
804 Set to C<'mail'> to check URLs with C<mail_url_callback>, rather than the
805 built in attribute rules: suitable for HTML from an email message. Ignored
806 if a B<url_callback> is given.
807  
808 =item B<delete_defang_content>
809  
810 Normally defanged tags are turned into comments and prefixed by defang_,
811 and defanged styles are surrounded by /* ... */. If this is set to
812 true, then defanged content is deleted instead
813  
814 =item B<Debug>
815  
816 If set, prints debugging output.
817  
818 =back
819  
820 =back
821  
822 =cut
823  
824 36 ▶sub new {
Subroutine new: called CC=12 SCAR=25.2
Pod documented
825 36 my $Proto = shift;
826 36 ▶ my $Class = ref($Proto) || $Proto;
Condition33%1/3
ref $Proto || $Proto
l!l&&r!l&&!r
0360
MC/DC0%0/2
ref $Proto || $Proto
ref $Proto $Proto
Truth table33%1/3
A || B
A= ref $ProtoB= $Proto
ABresult
1X1
011
000
827  
828 36 my %Opts = @_;
829  
830 my ($tags_to_callback, $attribs_to_callback, $empty_tags_to_collapse, $mismatched_tags_to_fix)
831 36 = @Opts{qw(tags_to_callback attribs_to_callback empty_tags_to_collapse mismatched_tags_to_fix)};
832 36 my %tags_to_callback;
833 36 ▶ %tags_to_callback = map { $_ => 1 } @$tags_to_callback if $tags_to_callback;
Branch: 1 branch
BranchTrueFalseTotal
if $tags_to_callback 12 24 36
834 36 my %attribs_to_callback;
835 0 ▶ %attribs_to_callback = map { $_ => 1 } @$attribs_to_callback if $attribs_to_callback;
Branch: 1 branch
BranchTrueFalseTotal
if $attribs_to_callback 0 36 36
836 36 my %empty_tags_to_collapse;
837 0 ▶ %empty_tags_to_collapse = map { $_ => 1 } @$empty_tags_to_collapse if $empty_tags_to_collapse;
Branch: 1 branch
BranchTrueFalseTotal
if $empty_tags_to_collapse 0 36 36
838 36 my %mismatched_tags_to_fix = %MismatchedTags;
839 36 ▶ %mismatched_tags_to_fix = map { $_ => 1 } @$mismatched_tags_to_fix if $mismatched_tags_to_fix;
Branch: 1 branch
BranchTrueFalseTotal
if $mismatched_tags_to_fix 1 35 36
840  
841 36 ▶ !defined $Opts{scope_id} || $Opts{scope_id} =~ /^[A-Za-z][A-Za-z0-9_-]*$/
Branch: 1 branch
BranchTrueFalseTotal
not defined $Opts{"scope_id"} or $Opts{"scope_id"} =~ /^[A-Za-z][A-Za-z0-9_-]*$/ or Carp::croak(qq[Invalid scope_id: $Opts{"scope_id"}]) 35 1 36
Condition100%3/3
not defined $Opts{"scope_id"} or $Opts{"scope_id"} =~ /^[A-Za-z][A-Za-z0-9_-]*$/
l!l&&r!l&&!r
3321
MC/DC100%2/2
not defined $Opts{"scope_id"} or $Opts{"scope_id"} =~ /^[A-Za-z][A-Za-z0-9_-]*$/
not defined $Opts{"scope_id"} $Opts{"scope_id"} =~ /^[A-Za-z][A-Za-z0-9_-]*$/
Truth table100%3/3
not(A) or B
A= not defined $Opts{"scope_id"}B= $Opts{"scope_id"} =~ /^[A-Za-z][A-Za-z0-9_-]*$/
ABresult
1X1
011
000
842 or Carp::croak("Invalid scope_id: $Opts{scope_id}");
843  
844 35 my $url_callback = $Opts{url_callback};
845 35 ▶ if (!$url_callback && defined $Opts{url_policy}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $url_callback and defined $Opts{"url_policy"}) 3 32 35
Condition100%3/3
not $url_callback and defined $Opts{"url_policy"}
!ll&&!rl&&r
3293
MC/DC100%2/2
not $url_callback and defined $Opts{"url_policy"}
not $url_callback defined $Opts{"url_policy"}
Truth table100%3/3
not(A) and B
A= not $url_callbackB= defined $Opts{"url_policy"}
ABresult
0X0
100
111
846 3 ▶ $Opts{url_policy} eq 'mail'
Branch: 1 branch
BranchTrueFalseTotal
$Opts{"url_policy"} eq "mail" or Carp::croak(qq[Unknown url_policy: $Opts{"url_policy"}]) 2 1 3
847 or Carp::croak("Unknown url_policy: $Opts{url_policy}");
848 2 $url_callback = \&mail_url_callback;
849 }
850  
851 my $Self = {
852 defang_string => 'defang_',
853 defang_re => qr/^defang_/,
854 defang_default => (defined $Opts{defang_default} ? $Opts{defang_default} : DEFANG_DEFAULT),
855 allow_double_defang => $Opts{allow_double_defang},
856 tags_to_callback => \%tags_to_callback,
857 tags_callback => $Opts{tags_callback},
858 attribs_to_callback => \%attribs_to_callback,
859 attribs_callback => $Opts{attribs_callback},
860 url_callback => $url_callback,
861 css_callback => $Opts{css_callback},
862 content_callback => $Opts{content_callback},
863 mismatched_tags_to_fix => \%mismatched_tags_to_fix,
864 fix_mismatched_tags => $Opts{fix_mismatched_tags},
865 context => $Opts{context},
866 opened_tags => [],
867 opened_tags_count => {},
868 closed_into_block_tags => [],
869 empty_tags_to_collapse => \%empty_tags_to_collapse,
870 quiet => $Opts{quiet},
871 delete_defang_content => $Opts{delete_defang_content},
872 extract_styles => $Opts{extract_styles},
873 scope_id => $Opts{scope_id},
874 extracted_styles => '',
875 body_style => '',
876 Debug => $Opts{Debug},
877 34 ▶ };
Branch: 1 branch
BranchTrueFalseTotal
defined $Opts{'defang_default'} ? : 0 34 34
878  
879 34 bless ($Self, $Class);
880 34 return $Self;
881 }
882  
883 =item I<HTML::Defang-E<gt>new_bodyonly(%Options)>
884  
885 Constructs a new HTML::Defang object that has the following
886 implicit options
887  
888 =over 4
889  
890 =item B<fix_mismatched_tags = 1>
891  
892 =item B<delete_defang_content = 1>
893  
894 =item B<tags_to_callback = [ qw(html head link body meta title bgsound base) ]>
895  
896 =item B<tags_callback = { ... remove all above tags and related content ... }>
897  
898 =item B<url_callback = { ... explicity DEFANG_NONE to leave everything alone ... }>
899  
900 =back
901  
902 Basically this is a easy way to remove all html boiler plate
903 content and return only the html body content. That includes any
904 C<< <base> >>, which would otherwise change how every relative URL around
905 the content resolves once it's embedded in another page.
906  
907 =cut
908  
909 1 ▶sub new_bodyonly {
Subroutine new_bodyonly: called CC=1 SCAR=0.0
Pod documented
910 return shift->new(
911 fix_mismatched_tags => 1,
912 delete_defang_content => 1,
913 tags_to_callback => [ qw(html head link body meta title bgsound base) ],
914 10 ▶ tags_callback => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
915 10 my (undef, $Defang, $Angle, $lcTag, $IsEndTag, $AttributeHash, $AttributesEnd, $HtmlR, $OutR) = @_;
916 10 ▶ $$HtmlR =~ m{\G.*?(?=</title|</head)}gcis if $lcTag eq 'title' && !$IsEndTag;
Branch: 1 branch
BranchTrueFalseTotal
if $lcTag eq "title" and not $IsEndTag 1 9 10
Condition100%3/3
$lcTag eq "title" and not $IsEndTag
!ll&&!rl&&r
811
MC/DC100%2/2
$lcTag eq "title" and not $IsEndTag
$lcTag eq "title" not $IsEndTag
Truth table100%3/3
A and not(B)
A= $lcTag eq "title"B= not $IsEndTag
ABresult
0X0
100
111
917 10 return DEFANG_ALWAYS;
918 },
919 2 ▶ url_callback => sub { return DEFANG_NONE; },
Subroutine __ANON__: called CC=1 SCAR=0.0
920 @_
921 1 );
922 }
923  
924 =item I<HTML::Defang-E<gt>new_quote(%Options)>
925  
926 Constructs a new HTML::Defang object for quoting the HTML body of an email
927 message inside another one, as in a reply or forward. Use it with
928 C<quote>. It has the following implicit options, overridable as usual:
929  
930 =over 4
931  
932 =item B<fix_mismatched_tags = 1>, B<delete_defang_content = 1>, B<quiet = 1>
933  
934 =item B<extract_styles = 1>
935  
936 =item B<scope_id = 'qt'>
937  
938 =item B<url_policy = 'mail'>
939  
940 =item B<tags_to_callback = [ qw(html head link body meta title bgsound base) ]>
941  
942 =item B<tags_callback = { ... remove all above tags and related content, keeping the body's style for C<quote> ... }>
943  
944 =back
945  
946 =cut
947  
948 1 ▶sub new_quote {
Subroutine new_quote: called CC=1 SCAR=0.0
Pod documented
949 return shift->new(
950 1 fix_mismatched_tags => 1,
951 delete_defang_content => 1,
952 quiet => 1,
953 extract_styles => 1,
954 scope_id => 'qt',
955 url_policy => 'mail',
956 tags_to_callback => [ qw(html head link body meta title bgsound base) ],
957 tags_callback => \&quote_tags_callback,
958 @_
959 );
960 }
961  
962 10 ▶sub quote_tags_callback {
Subroutine quote_tags_callback: called CC=5 SCAR=16.1
Pod undocumented
963 10 my (undef, $Defang, $Angle, $lcTag, $IsEndTag, $AttributeHash, $AttributesEnd, $HtmlR, $OutR) = @_;
964 10 ▶ $$HtmlR =~ m{\G.*?(?=</title|</head)}gcis if $lcTag eq 'title' && !$IsEndTag;
Branch: 1 branch
BranchTrueFalseTotal
if $lcTag eq "title" and not $IsEndTag 1 9 10
Condition100%3/3
$lcTag eq "title" and not $IsEndTag
!ll&&!rl&&r
811
MC/DC100%2/2
$lcTag eq "title" and not $IsEndTag
$lcTag eq "title" not $IsEndTag
Truth table100%3/3
A and not(B)
A= $lcTag eq "title"B= not $IsEndTag
ABresult
0X0
100
111
965 10 ▶ $Defang->{body_style} = $Defang->defang_body_style($AttributeHash, $HtmlR, $OutR)
Branch: 1 branch
BranchTrueFalseTotal
if $lcTag eq "body" and not $IsEndTag 1 9 10
Condition100%3/3
$lcTag eq "body" and not $IsEndTag
!ll&&!rl&&r
811
MC/DC100%2/2
$lcTag eq "body" and not $IsEndTag
$lcTag eq "body" not $IsEndTag
Truth table100%3/3
A and not(B)
A= $lcTag eq "body"B= not $IsEndTag
ABresult
0X0
100
111
966 if $lcTag eq 'body' && !$IsEndTag;
967 10 return DEFANG_ALWAYS;
968 }
969  
970 # The <body>'s presentation as a style attribute value for whatever element
971 # replaces it, without the sizing and positioning a body uses to fill the
972 # window, which on an element within a page would clip or misplace it
973 11 my %BodyAttributeStyles = (bgcolor => 'background-color', text => 'color');
974  
975 1 ▶sub defang_body_style {
Subroutine defang_body_style: called CC=8 SCAR=22.0
Pod undocumented
976 1 my ($Self, $AttributeHash, $HtmlR, $OutR) = @_;
977  
978 1 my @Styles;
979 1 for my $Attr (sort keys %BodyAttributeStyles) {
980 2 my $ValR = $AttributeHash->{$Attr};
981 push @Styles, "$BodyAttributeStyles{$Attr}: $$ValR"
982 2 ▶ if $ValR && defined $$ValR && $$ValR =~ $Rules{color};
Branch: 1 branch
BranchTrueFalseTotal
if $ValR and defined $$ValR and $$ValR =~ /$Rules{"color"}/ 2 0 2
Condition33%2/6
$ValR and defined $$ValR and $$ValR =~ /$Rules{"color"}/
!ll&&!rl&&r
002
$ValR and defined $$ValR
!ll&&!rl&&r
002
MC/DC0%0/3
$ValR and defined $$ValR and $$ValR =~ /$Rules{"color"}/
$ValR defined $$ValR $$ValR =~ /$Rules{"color"}/
Truth table25%1/4
A and B and C
A= $ValRB= defined $$ValRC= $$ValR =~ /$Rules{"color"}/
ABCresult
0XX0
10X0
1100
1111
983 }
984  
985 1 ▶ if (my $ValR = $AttributeHash->{style}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ValR = $AttributeHash->{"style"}) 1 0 1
986 1 my $UserCallback = $Self->{css_callback};
987 1 ▶ local $Self->{css_callback} = sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
988 1 my ($Context, $Defang, $Selectors, $SelectorRules) = @_;
989 1 ▶ $UserCallback->(@_) if $UserCallback;
Branch: 1 branch
BranchTrueFalseTotal
if $UserCallback 0 1 1
990 1 for my $KeyValueRule (map { @$_ } map { @$_ } @$SelectorRules) {
991 4 ▶ $KeyValueRule->[2] = DEFANG_ALWAYS
Branch: 1 branch
BranchTrueFalseTotal
if $KeyValueRule->[0] =~ /^\s*(?:(?:min-|max-)?height|overflow(?:-[xy])?|position)\s*$/i 2 2 4
992 if $KeyValueRule->[0] =~ /^\s*(?:(?:min-|max-)?height|overflow(?:-[xy])?|position)\s*$/i;
993 }
994 1 };
995 1 ▶ my $Style = $Self->defang_style_text(defined $$ValR ? $$ValR : '', 'body', 1, $AttributeHash, $HtmlR, $OutR);
Branch: 1 branch
BranchTrueFalseTotal
defined $$ValR ? : 1 0 1
996 1 $Style =~ s/^[\s;]+|[\s;]+$//g;
997 1 ▶ push @Styles, $Style if length $Style;
Branch: 1 branch
BranchTrueFalseTotal
if length $Style 1 0 1
998 }
999  
1000 1 return join '; ', @Styles;
1001 }
1002  
1003 =item I<quote($InputHtml)>
1004  
1005 Defang the HTML body of an email message for quoting, with an object from
1006 C<new_quote>. Returns a hash reference of:
1007  
1008 =over 4
1009  
1010 =item B<html>
1011  
1012 The body's content, to put inside an element with the B<scope_id>.
1013  
1014 =item B<styles>
1015  
1016 The message's CSS, scoped to that element, for a C<< <style> >> in the
1017 C<< <head> >> of the new message.
1018  
1019 =item B<body_style>
1020  
1021 A CSS declaration list from the original C<< <body> >>, for that element's
1022 C<style> attribute. It is not HTML escaped.
1023  
1024 =back
1025  
1026 For example:
1027  
1028 my $Quote = HTML::Defang->new_quote->quote($OriginalHtml);
1029 my $Html = qq{<!DOCTYPE html><html><head><style>$Quote->{styles}</style></head><body>}
1030 . qq{<p>My reply</p><blockquote type="cite" id="qt" style="}
1031 . escape_html($Quote->{body_style}) . qq{">$Quote->{html}</blockquote></body></html>};
1032  
1033 =cut
1034  
1035 2 ▶sub quote {
Subroutine quote: called CC=1 SCAR=0.0
Pod documented
1036 2 my ($Self, $Html) = @_;
1037  
1038 2 my $Out = $Self->defang($Html);
1039  
1040 return {
1041 html => $Out,
1042 styles => $Self->{extracted_styles},
1043 body_style => $Self->{body_style},
1044 2 };
1045 }
1046  
1047 =item I<mail_url_callback(...)>
1048  
1049 A B<url_callback> (see C<url_callback>) for HTML from an email message,
1050 used by C<< url_policy => 'mail' >>. A link (C<href>) may go to an http(s),
1051 mailto, tel or cid URL, or an anchor in the message. Anything the client
1052 loads itself (C<src>, C<background>, CSS C<url()>) may only come from an
1053 http(s) or cid URL, or be an inline raster image in a C<data:> URL. Anything
1054 else is defanged, including relative URLs, which have nothing to resolve
1055 against in a message.
1056  
1057 =cut
1058  
1059 11 my $MailLinkRE = qr/^(?:(?:https?|mailto|tel|cid):|#)/i;
1060 11 my $MailLoadRE = qr{^(?:(?:https?|cid):|data:image/(?:png|gif|jpe?g|webp|bmp);base64,)}i;
1061  
1062 20 ▶sub mail_url_callback {
Subroutine mail_url_callback: called CC=4 SCAR=13.9
Pod documented
1063 20 my (undef, $Defang, $lcTag, $lcAttrKey, $AttrValR) = @_;
1064  
1065 # The stripped value is what a browser would see, with entities, escapes,
1066 # control chars and leading space already undone
1067 20 my $Url = $Defang->strip_attribute($$AttrValR);
1068 20 ▶ my $IsLink = defined $lcAttrKey && $lcAttrKey eq 'href';
Condition100%3/3
defined $lcAttrKey && $lcAttrKey eq 'href'
!ll&&!rl&&r
1118
MC/DC100%2/2
defined $lcAttrKey && $lcAttrKey eq 'href'
defined $lcAttrKey $lcAttrKey eq 'href'
Truth table100%3/3
A && B
A= defined $lcAttrKeyB= $lcAttrKey eq 'href'
ABresult
0X0
100
111
1069  
1070 20 ▶ return $Url =~ ($IsLink ? $MailLinkRE : $MailLoadRE) ? DEFANG_NONE : DEFANG_ALWAYS;
Branch: 2 branches
BranchTrueFalseTotal
$Url =~ ($IsLink ? $MailLinkRE : $MailLoadRE) ? : 12 8 20
$IsLink ? : 8 12 20
1071 }
1072  
1073 =back
1074  
1075 =cut
1076  
1077 =head1 CALLBACK METHODS
1078  
1079 =over 4
1080  
1081 =cut
1082  
1083 =item B<COMMON PARAMETERS>
1084  
1085 A number of the callbacks share the same parameters. These common parameters are documented here. Certain variables may have specific meanings in certain callbacks, so be sure to check the documentation for that method first before referring this section.
1086  
1087 =over 4
1088  
1089 =item I<$context>
1090  
1091 You can pass an arbitrary scalar as a 'context' value that's then passed as the first parameter to all callback functions. Most commonly this is something like '$Self'
1092  
1093 =item I<$Defang>
1094  
1095 Current HTML::Defang instance
1096  
1097 =item I<$OpenAngle>
1098  
1099 Opening angle(<) sign of the current tag.
1100  
1101 =item I<$lcTag>
1102  
1103 Lower case version of the HTML tag that is currently being parsed.
1104  
1105 =item I<$IsEndTag>
1106  
1107 Has the value '/' if the current tag is a closing tag.
1108  
1109 =item I<$AttributeHash>
1110  
1111 A reference to a hash containing the attributes of the current tag and
1112 their values. Each value is a scalar reference to the value, rather
1113 than just a scalar value. You can add attributes (remember to make it a
1114 scalar ref, eg $AttributeHash{"newattr"} = \"newval"), delete attributes,
1115 or modify attribute values in this hash, and any changes you make will
1116 be incorporated into the output HTML stream.
1117  
1118 The attribute values will have any entity references decoded before
1119 being passed to you, and any unsafe values we be re-encoded back into
1120 the HTML stream.
1121  
1122 So for instance, the tag:
1123  
1124 <div title="&lt;&quot;Hi there &#x003C;">
1125  
1126 Will have the attribute hash:
1127  
1128 { title => \q[<"Hi there <] }
1129  
1130 And will be turned back into the HTML on output:
1131  
1132 <div title="&lt;&quot;Hi there &lt;">
1133  
1134 =item I<$CloseAngle>
1135  
1136 Anything after the end of last attribute including the closing HTML angle(>)
1137  
1138 =item I<$HtmlR>
1139  
1140 A scalar reference to the input HTML. The input HTML is parsed using
1141 m/\G$SomeRegex/c constructs, so to continue from where HTML:Defang left,
1142 clients can use m/\G$SomeRegex/c for further processing on the input. This
1143 will resume parsing from where HTML::Defang left. One can also use the
1144 pos() function to determine where HTML::Defang left off. This combined
1145 with the add_to_output() method should give reasonable flexibility for
1146 the client to process the input.
1147  
1148 =item I<$OutR>
1149  
1150 A scalar reference to the processed output HTML so far.
1151  
1152 =back
1153  
1154 =item I<tags_callback($context, $Defang, $OpenAngle, $lcTag, $IsEndTag, $AttributeHash, $CloseAngle, $HtmlR, $OutR)>
1155  
1156 If $Defang->{tags_callback} exists, and HTML::Defang has parsed a tag preset in $Defang->{tags_to_callback}, the above callback is made to the client code. The return value of this method determines whether the tag is defanged or not. More details below.
1157  
1158 =over 4
1159  
1160 =item B<Return values>
1161  
1162 =over 4
1163  
1164 =item DEFANG_NONE
1165  
1166 The current tag will not be defanged.
1167  
1168 =item DEFANG_ALWAYS
1169  
1170 The current tag will be defanged.
1171  
1172 =item DEFANG_DEFAULT
1173  
1174 The current tag will be processed normally by HTML:Defang as if there was no callback method specified.
1175  
1176 =back
1177  
1178 =back
1179  
1180 =item I<attribs_callback($context, $Defang, $lcTag, $lcAttrKey, $AttrVal, $HtmlR, $OutR)>
1181  
1182 If $Defang->{attribs_callback} exists, and HTML::Defang has parsed an attribute present in $Defang->{attribs_to_callback}, the above callback is made to the client code. The return value of this method determines whether the attribute is defanged or not. More details below.
1183  
1184 =over 4
1185  
1186 =item B<Method parameters>
1187  
1188 =over 4
1189  
1190 =item I<$lcAttrKey>
1191  
1192 Lower case version of the HTML attribute that is currently being parsed.
1193  
1194 =item I<$AttrVal>
1195  
1196 Reference to the HTML attribute value that is currently being parsed.
1197  
1198 See $AttributeHash for details of decoding.
1199  
1200 =back
1201  
1202 =item B<Return values>
1203  
1204 =over 4
1205  
1206 =item DEFANG_NONE
1207  
1208 The current attribute will not be defanged.
1209  
1210 =item DEFANG_ALWAYS
1211  
1212 The current attribute will be defanged.
1213  
1214 =item DEFANG_DEFAULT
1215  
1216 The current attribute will be processed normally by HTML:Defang as if there was no callback method specified.
1217  
1218 =back
1219  
1220 =back
1221  
1222 =item I<url_callback($context, $Defang, $lcTag, $lcAttrKey, $AttrVal, $AttributeHash, $HtmlR, $OutR)>
1223  
1224 If $Defang->{url_callback} exists, and HTML::Defang has parsed a URL, the above callback is made to the client code. The return value of this method determines whether the attribute containing the URL is defanged or not. URL callbacks can be made from <style> tags as well style attributes, in which case the particular style declaration will be commented out. More details below.
1225  
1226 =over 4
1227  
1228 =item B<Method parameters>
1229  
1230 =over 4
1231  
1232 =item I<$lcAttrKey>
1233  
1234 Lower case version of the HTML attribute that is currently being parsed. However if this callback is made as a result of parsing a URL in a style attribute, $lcAttrKey will be set to the string I<style>, or will be set to I<undef> if this callback is made as a result of parsing a URL inside a style tag.
1235  
1236 =item I<$AttrVal>
1237  
1238 Reference to the URL value that is currently being parsed.
1239  
1240 =item I<$AttributeHash>
1241  
1242 A reference to a hash containing the attributes of the current tag and their values. Each value is a scalar reference to the value,
1243 rather than just a scalar value. You can add attributes (remember to make it a scalar ref, eg $AttributeHash{"newattr"} = \"newval"), delete attributes, or modify attribute values in this hash, and any changes you make will be incorporated into the output HTML stream. Will be set to I<undef> if the callback is made due to URL in a <style> tag or attribute.
1244  
1245 =back
1246  
1247 =item B<Return values>
1248  
1249 =over 4
1250  
1251 =item DEFANG_NONE
1252  
1253 The current URL will not be defanged.
1254  
1255 =item DEFANG_ALWAYS
1256  
1257 The current URL will be defanged.
1258  
1259 =item DEFANG_DEFAULT
1260  
1261 The current URL will be processed normally by HTML:Defang as if there was no callback method specified.
1262  
1263 =back
1264  
1265 =back
1266  
1267 =item I<css_callback($context, $Defang, $Selectors, $SelectorRules, $lcTag, $IsAttr, $OutR)>
1268  
1269 If $Defang->{css_callback} exists, and HTML::Defang has parsed a <style> tag or style attribtue, the above callback is made to the client code. The return value of this method determines whether a particular declaration in the style rules is defanged or not. More details below.
1270  
1271 =over 4
1272  
1273 =item B<Method parameters>
1274  
1275 =over 4
1276  
1277 =item I<$Selectors>
1278  
1279 Reference to an array containing the selectors in a style tag or attribute.
1280  
1281 A callback may rewrite a selector in place (for instance to scope it by
1282 prefixing it), but must not add or remove entries. Each C<@media> block
1283 appears as an entry for its C<@media ...> prelude and an empty entry for
1284 its closing brace, and each selector inside it is the prelude and the
1285 selector joined with a C<\0> character, of which only the part after the
1286 last C<\0> is output.
1287  
1288 =item I<$SelectorRules>
1289  
1290 Reference to an array containing the style declaration blocks of all selectors in a style tag or attribute. Consider the below CSS:
1291  
1292 a { b:c; d:e}
1293 j { k:l; m:n}
1294  
1295 The declaration blocks will get parsed into the following data structure:
1296  
1297 [
1298 [
1299 [ "b", "c", DEFANG_DEFAULT ],
1300 [ "d", "e", DEFANG_DEFAULT ]
1301 ],
1302 [
1303 [ "k", "l", DEFANG_DEFAULT ],
1304 [ "m", "n", DEFANG_DEFAULT ]
1305 ]
1306 ]
1307  
1308 So, generally each property:value pair in a declaration is parsed into an array of the form
1309  
1310 ["property", "value", X]
1311  
1312 where X can be DEFANG_NONE, DEFANG_ALWAYS or DEFANG_DEFAULT, and DEFANG_DEFAULT the default value. A client can manipulate this value to instruct HTML::Defang to defang this property:value pair.
1313  
1314 DEFANG_NONE - Do not defang
1315  
1316 DEFANG_ALWAYS - Defang the style:property value
1317  
1318 DEFANG_DEFAULT - Process this as if there is no callback specified
1319  
1320 =item I<$IsAttr>
1321  
1322 True if the currently processed item is a style attribute. False if the currently processed item is a style tag.
1323  
1324 =back
1325  
1326 =back
1327  
1328 =back
1329  
1330 =cut
1331  
1332 =head1 METHODS
1333  
1334 =over 4
1335  
1336 =item B<PUBLIC METHODS>
1337  
1338 =over 4
1339  
1340 =cut
1341  
1342 =item I<defang($InputHtml, \%Opts)>
1343  
1344 Cleans up $InputHtml of any executable code including scripting, embedded objects, applets, etc., and defang any XSS attacks.
1345  
1346 =over 4
1347  
1348 =item B<Method parameters>
1349  
1350 =over 4
1351  
1352 =item I<$InputHtml>
1353  
1354 The input HTML string that needs to be sanitized.
1355  
1356 =back
1357  
1358 =back
1359  
1360 Returns the cleaned HTML. If fix_mismatched_tags is set, any tags that appear in @$mismatched_tags_to_fix that are unbalanced are automatically commented or closed.
1361  
1362 =cut
1363 364 ▶sub defang {
Subroutine defang: called CC=67 SCAR=43.1
Pod documented
1364 364 my $Self = shift;
1365  
1366 364 my $I = shift;
1367 364 my $Opts = shift;
1368  
1369 364 my $Debug = $Self->{Debug};
1370  
1371 364 my $HeaderCharset = $Opts->{header_charset};
1372 364 ▶ warn("defang HeaderCharset=$HeaderCharset") if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 364 364
1373 364 my $FallbackCharset = $Opts->{fallback_charset};
1374 364 ▶ warn("defang FallbackCharset=$FallbackCharset") if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 364 364
1375  
1376 # Per document results, reset by the outermost call
1377 364 ▶ @$Self{qw(extracted_styles body_style)} = ('', '') if ++$Self->{Reentrant} == 1;
Branch: 1 branch
BranchTrueFalseTotal
if ++$Self->{"Reentrant"} == 1 364 0 364
1378  
1379 # Output buffer
1380 364 ▶ local $Self->{OutR} = $Opts->{add_to_existing} ? $Self->{OutR} : \(my $O = "");
Branch: 1 branch
BranchTrueFalseTotal
$Opts->{'add_to_existing'} ? : 0 364 364
1381 364 my $OutR = $Self->{OutR};
1382  
1383 # Get encoded characters
1384 # $Self->{Charset} = $Self->get_applicable_charset($_, $HeaderCharset, $FallbackCharset);
1385 # warn("defang Charset=$Self->{Charset}") if $Self->{Debug};
1386  
1387 # if ($Self->{Charset}) {
1388 # $I =~ s/(.)/chr(ord($1) & 127)/ge if $Self->{Charset} eq "US-ASCII";
1389 # my $Encoder = Encode::Encoder->new($I, $Self->{Charset});
1390 # $I = $Encoder->bytes($Self->{Charset});
1391 # }
1392  
1393 # We pass a ref to $I to each callback. It should
1394 # never be modified because we use a m/\G.../gc loop
1395 # on it. If possible, stop people modifying it
1396 364 ▶ readonly_on($I) if $HasScalarReadonly;
Branch: 1 branch
BranchTrueFalseTotal
if $HasScalarReadonly 0 364 364
1397  
1398 # It seems regexp matching on perl unicode strings can be *way*
1399 # slower than byte string (defang 1M email = 100 seconds unicode,
1400 # 5 seconds bytes).
1401 # So we're going to do a bit of a hack. Engaged "use bytes" to do
1402 # byte matching everywhere, but since we know we'll be matching
1403 # on correct boundaries to make up full code points in utf-8, we'll
1404 # turn on the magic utf-8 flag again for those values
1405 364 my $UTF8Input = $Self->{UTF8Input} = Encode::is_utf8($I);
1406  
1407 # Force byte matching everywhere (see above)
1408 11 ▶ use bytes;
Subroutine BEGIN: called CC=1 SCAR=0.0
1409  
1410 364 ▶ Carp::cluck() if !defined $I;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $I 0 364 364
1411  
1412 # Strip all NUL chars
1413 364 $I =~ s/\0//g;
1414  
1415 # This parser uses standard /\G.../gc matching, so have to be careful
1416 # to not reset pos() on the string
1417 #
1418 # Previously we tried an "eating" parser (s/^.../, or /^.../ + substr),
1419 # which in theory should be fast with perls internal string offset
1420 # feature, but it seems offset doesn't work on unicode strings,
1421 # so you end up with a slow parser because of string reallocations
1422  
1423 364 while (1) {
1424  
1425 # walk to next < (testing in 5.8.8 shows .*? is faster than [^<]* or [^<]*?)
1426 1583 ▶ if ($I =~ m{\G(.*?)<}gcso) {
Branch: 1 branch
BranchTrueFalseTotal
if ($I =~ /\G(.*?)</cogs) 1219 364 1583
1427  
1428 1219 my $Content = $1;
1429  
1430 # Call content callback if present
1431 $Self->{content_callback}->($Self->{context}, $Self, \$Content)
1432 1219 ▶ if $Self->{content_callback};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"content_callback"} 0 1219 1219
1433  
1434 # Everything before tag goes into the output
1435 1219 $$OutR .= $Content;
1436  
1437 # All tags default to open/close with </>
1438 1219 my ($OpenAngle, $CloseAngle) = ('<', '>');
1439 1219 ▶ my $IsEndTag = $I =~ m{\G/}gcso ? '/' : '';
Branch: 1 branch
BranchTrueFalseTotal
$I =~ m[\G/]cogs ? : 278 941 1219
1440  
1441 # It's a standard tag
1442 1219 ▶ if ($I =~ m{\G($TagNameRE)}gcso) {
Branch: 3 branches
BranchTrueFalseTotal
if ($I =~ /\G($TagNameRE)/cogs) { } 1176 43 1219
elsif ($I =~ /\G(!)((?:\[CDATA\[|--)?)/cgis) { } 33 10 43
elsif ($I =~ /\G(\?)/cgs) { } 8 2 10
1443  
1444 1176 my $Tag = $1;
1445 1176 ▶ my $TagTrail = $I =~ m{\G([\s/]+)}gcso ? $1 : '';
Branch: 1 branch
BranchTrueFalseTotal
$I =~ m[\G([\s/]+)]cogs ? : 624 552 1176
1446  
1447 1176 ▶ warn "defang IsEndTag=$IsEndTag Tag=$Tag" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 1176 1176
1448  
1449 # Skip attribute parsing if none
1450 1176 my @Attributes;
1451 1176 ▶ goto NoParseAttributes if $I =~ m{\G>}gcso;
Branch: 1 branch
BranchTrueFalseTotal
if $I =~ /\G>/cogs 557 619 1176
1452  
1453 # Pull off any trailing component after the tag
1454 # Now match all key=value attributes
1455 619 ▶ while ($I =~ m{\G(?:($AttrKeyStartLineRE)(\s*))?(?:(=\s*)($AttrValRE)(\s*))?}gcso) {
Branch: 1 branch
BranchTrueFalseTotal
if ($I =~ /\G(?:($AttrKeyStartLineRE)(\s*))?(?:(=\s*)($AttrValRE)(\s*))?/cogs) 1386 0 1386
1456  
1457 1386 ▶ last if !defined($1) && !defined($4);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $1 or defined $4 619 767 1386
Condition100%3/3
defined $1 or defined $4
l!l&&r!l&&!r
7652619
MC/DC100%2/2
defined $1 or defined $4
defined $1 defined $4
Truth table100%3/3
A or B
A= defined $1B= defined $4
ABresult
1X1
011
000
1458 767 my ($Attribute, $AttrTrail, $Equals, $AttrVal, $AttrValTrail) = ($1, $2, $3, $4, $5);
1459 767 my ($AttrQuote, $AttrValWithoutQuote) = '';
1460 767 ▶ if (defined($4) && $4 =~ /^([`"']?)(.*)\1$/s) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $4 and $4 =~ /^([`"']?)(.*)\1$/s) 755 12 767
Condition66%2/3
defined $4 and $4 =~ /^([`"']?)(.*)\1$/s
!ll&&!rl&&r
120755
MC/DC50%1/2
defined $4 and $4 =~ /^([`"']?)(.*)\1$/s
defined $4 $4 =~ /^([`"']?)(.*)\1$/s
Truth table66%2/3
A and B
A= defined $4B= $4 =~ /^([`"']?)(.*)\1$/s
ABresult
0X0
100
111
1461 # IE supports `, but nothing else does, turn it into "
1462 755 ▶ $AttrQuote = $1 eq '`' ? '"' : $1;
Branch: 1 branch
BranchTrueFalseTotal
$1 eq '`' ? : 6 749 755
1463 755 $AttrValWithoutQuote = $2;
1464 }
1465  
1466 # Turn on utf-8 for things that might be
1467 767 ▶ Encode::_utf8_on($Attribute) if $UTF8Input;
Branch: 1 branch
BranchTrueFalseTotal
if $UTF8Input 4 763 767
1468 767 ▶ Encode::_utf8_on($AttrValWithoutQuote) if $UTF8Input;
Branch: 1 branch
BranchTrueFalseTotal
if $UTF8Input 4 763 767
1469  
1470 767 push @Attributes, [ $Attribute, $AttrTrail, $Equals, $AttrQuote, $AttrValWithoutQuote, $AttrQuote, $AttrValTrail ];
1471 767 ▶ warn "defang AttributeKey=$1 AttrQuote=$AttrQuote AttributeValue=$Attribute" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 767 767
1472 }
1473  
1474 # Better be at end of attributes, or attach our own ending tag
1475 619 ▶ if ($I =~ m{\G(?:(\s*[/\\]*\s*(?:--)?\s*)?>|([\s/-]*))}gcs) {
Branch: 1 branch
BranchTrueFalseTotal
if ($I =~ m(\G(?:(\s*[/\\]*\s*(?:--)?\s*)?>|([\s/-]*)))cgs) 613 6 619
1476 613 ▶ $CloseAngle = $1 ? $1 . '>' : ($2 ? $2 . '>' : '>');
Branch: 2 branches
BranchTrueFalseTotal
$1 ? : 13 600 613
$2 ? : 0 600 600
1477 }
1478  
1479 NoParseAttributes:
1480 1176 my $Defang = DEFANG_ALWAYS;
1481  
1482 1176 my $lcTag = lc $Tag;
1483 1176 my $TagOps = $Tags{$lcTag};
1484  
1485 # Process this tag
1486 1176 ▶ if (!exists $Self->{tags_to_callback}->{$lcTag} && ref $TagOps eq "CODE") {
Branch: 1 branch
BranchTrueFalseTotal
if (not exists $Self->{'tags_to_callback'}{$lcTag} and ref $TagOps eq 'CODE') { } 293 883 1176
Condition100%3/3
not exists $Self->{"tags_to_callback"}{$lcTag} and ref $TagOps eq "CODE"
!ll&&!rl&&r
115768293
MC/DC100%2/2
not exists $Self->{"tags_to_callback"}{$lcTag} and ref $TagOps eq "CODE"
not exists $Self->{"tags_to_callback"}{$lcTag} ref $TagOps eq "CODE"
Truth table100%3/3
not(A) and B
A= not exists $Self->{"tags_to_callback"}{$lcTag}B= ref $TagOps eq "CODE"
ABresult
0X0
100
111
1487  
1488 293 ▶ warn "process_tag Found CODE reference" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 293 293
1489 293 $Defang = $Self->${TagOps}($OutR, \$I, $TagOps, \$OpenAngle, $IsEndTag, $lcTag, $TagTrail, \@Attributes, \$CloseAngle);
1490  
1491 } else {
1492  
1493 883 ▶ warn "process_tag Found regular tag" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 883 883
1494 883 $Defang = $Self->defang_attributes($OutR, \$I, $TagOps, \$OpenAngle, $IsEndTag, $lcTag, $TagTrail, \@Attributes, \$CloseAngle);
1495  
1496 }
1497 1176 ▶ die "Callback reset pos on Tag=$Tag IsEndTag=$IsEndTag" if !defined pos($I);
Branch: 1 branch
BranchTrueFalseTotal
unless defined pos $I 0 1176 1176
1498 1176 ▶ goto SkipOutput if delete $Self->{SkipTagOutput};
Branch: 1 branch
BranchTrueFalseTotal
if delete $Self->{"SkipTagOutput"} 14 1162 1176
1499 1162 ▶ warn "defang Defang=$Defang" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 1162 1162
1500  
1501 # RCDATA/RAWTEXT elements (title, textarea, noembed, noframes): their
1502 # content is opaque text to a browser, not HTML. Consume it verbatim
1503 # up to the matching end tag so we don't parse comments/tags inside
1504 # it (which would let an attacker smuggle a literal end tag + active
1505 # markup past the defanger). Skipped if a user tags_callback owns the
1506 # tag, since it is then responsible for the content.
1507 1162 ▶ if (!$IsEndTag && $RawTextTags{$lcTag}
Branch: 1 branch
BranchTrueFalseTotal
if (not $IsEndTag and $RawTextTags{$lcTag} and not exists $Self->{"tags_to_callback"}{$lcTag}) 12 1150 1162
Condition100%6/6
not $IsEndTag and $RawTextTags{$lcTag} and not exists $Self->{"tags_to_callback"}{$lcTag}
!ll&&!rl&&r
1148212
not $IsEndTag and $RawTextTags{$lcTag}
!ll&&!rl&&r
27187714
MC/DC100%3/3
not $IsEndTag and $RawTextTags{$lcTag} and not exists $Self->{"tags_to_callback"}{$lcTag}
not $IsEndTag $RawTextTags{$lcTag} not exists $Self->{"tags_to_callback"}{$lcTag}
Truth table100%4/4
not(A) and B and not(C)
A= not $IsEndTagB= $RawTextTags{$lcTag}C= not exists $Self->{"tags_to_callback"}{$lcTag}
ABCresult
0XX0
10X0
1100
1111
1508 && !exists $Self->{tags_to_callback}->{$lcTag}) {
1509 12 $Self->defang_rcdata_content(\$I, $lcTag);
1510 }
1511  
1512 # Build tag content, because if we defang, we have to remove --'s within it
1513  
1514 # @Attributes can have unicode values, but we're within "use bytes", so it's flattened ok
1515 1162 my $TagContent = $TagTrail . join("", grep { defined } map { @$_ } @Attributes);
1516  
1517 1162 ▶ if ($Self->{fix_mismatched_tags} && ($Defang == DEFANG_NONE)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Self->{"fix_mismatched_tags"} and $Defang == 0) 110 1052 1162
Condition100%3/3
$Self->{"fix_mismatched_tags"} and $Defang == 0
!ll&&!rl&&r
102725110
MC/DC100%2/2
$Self->{"fix_mismatched_tags"} and $Defang == 0
$Self->{"fix_mismatched_tags"} $Defang == 0
Truth table100%3/3
A and B
A= $Self->{"fix_mismatched_tags"}B= $Defang == 0
ABresult
0X0
100
111
1518 110 ▶ if (!$IsEndTag) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $IsEndTag) { } 80 30 110
1519 80 $Defang = $Self->open_tag(0, $OutR, \$I, $lcTag, \$TagContent);
1520 } else {
1521 30 $Defang = $Self->close_tag(0, $OutR, \$I, $lcTag);
1522 30 ▶ goto SkipOutput if $Defang == DEFANG_ALWAYS;
Branch: 1 branch
BranchTrueFalseTotal
if $Defang == 1 5 25 30
1523 }
1524 }
1525  
1526 # defang unknown tags
1527 1157 ▶ if ($Defang != DEFANG_NONE) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Defang != 0) 186 971 1157
1528 186 ▶ warn "defang Defanging $Tag" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 186 186
1529 186 ▶ if ($Self->{delete_defang_content}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Self->{'delete_defang_content'}) { } 22 164 186
1530 22 $OpenAngle = $IsEndTag = $Tag = $TagContent = $CloseAngle = '';
1531 } else {
1532 $Tag = $Self->{defang_string} . $Tag
1533 164 ▶ if $Self->{allow_double_defang} || $Tag !~ $Self->{defang_re};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"allow_double_defang"} or not $Tag =~ /$Self->{"defang_re"}/ 164 0 164
Condition33%1/3
$Self->{"allow_double_defang"} or not $Tag =~ /$Self->{"defang_re"}/
l!l&&r!l&&!r
01640
MC/DC0%0/2
$Self->{"allow_double_defang"} or not $Tag =~ /$Self->{"defang_re"}/
$Self->{"allow_double_defang"} not $Tag =~ /$Self->{"defang_re"}/
Truth table33%1/3
A or not(B)
A= $Self->{"allow_double_defang"}B= not $Tag =~ /$Self->{"defang_re"}/
ABresult
1X1
011
000
1534 164 $TagContent =~ s/--//g;
1535 164 $Tag =~ s/--//g;
1536 164 $OpenAngle =~ s/^</<!--/;
1537 164 $CloseAngle =~ s/>$/-->/;
1538 }
1539 }
1540  
1541 # And put it all back together into the output string
1542 1157 $$OutR .= $OpenAngle . $IsEndTag . $Tag . $TagContent . $CloseAngle;
1543 SkipOutput:
1544  
1545 # It's a comment of some sort. We are looking for regular HTML comment, XML CDATA section
1546 1176 } elsif ($I =~ m{\G(!)((?:\[CDATA\[|--)?)}gcis) {
1547  
1548 33 my ($Comment, $CommentDelim) = ($1, $2);
1549 33 ▶ warn "defang Comment=$Comment CommentDelim=$CommentDelim" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 33 33
1550  
1551 # Find the appropriate closing delimiter
1552 33 my $IsCDATA = $CommentDelim eq "[CDATA[";
1553 33 ▶ my $ClosingCommentDelim = $IsCDATA ? "]]" : $CommentDelim;
Branch: 1 branch
BranchTrueFalseTotal
$IsCDATA ? : 6 27 33
1554  
1555 33 ▶ warn "defang ClosingCommentDelim=$ClosingCommentDelim" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 33 33
1556  
1557 33 my ($CommentStartText, $CommentEndText) = ("--/*SC*/", "/*EC*/--");
1558  
1559 # Convert to regular HTML comment
1560 33 ▶ if (!$Self->{delete_defang_content}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($Self->{"delete_defang_content"}) 30 3 33
1561 30 $$OutR .= $OpenAngle . $Comment . $CommentStartText;
1562 }
1563  
1564 # Find closing comment
1565 33 ▶ if ($I =~ m{\G(.*?)(\Q$ClosingCommentDelim\E!?\s*)(>)}gcis || $I =~ m{\G(.*?)(--)(>)}gcis) {
Branch: 1 branch
BranchTrueFalseTotal
if ($I =~ /\G(.*?)(\Q$ClosingCommentDelim\E!?\s*)(>)/cgis or $I =~ /\G(.*?)(--)(>)/cgis) { } 27 6 33
Condition66%2/3
$I =~ /\G(.*?)(\Q$ClosingCommentDelim\E!?\s*)(>)/cgis or $I =~ /\G(.*?)(--)(>)/cgis
l!l&&r!l&&!r
2706
MC/DC50%1/2
$I =~ /\G(.*?)(\Q$ClosingCommentDelim\E!?\s*)(>)/cgis or $I =~ /\G(.*?)(--)(>)/cgis
$I =~ /\G(.*?)(\Q$ClosingCommentDelim\E!?\s*)(>)/cgis $I =~ /\G(.*?)(--)(>)/cgis
Truth table66%2/3
A or B
A= $I =~ /\G(.*?)(\Q$ClosingCommentDelim\E!?\s*)(>)/cgisB= $I =~ /\G(.*?)(--)(>)/cgis
ABresult
1X1
011
000
1566  
1567 27 my ( $StartTag, $CommentData, $ClosingTag, $CloseAngle ) =
1568 ( $CommentDelim, $1, $2, $3 );
1569  
1570 # Strip all HTML comment markers
1571 27 $StartTag =~ s/--//g;
1572 27 $CommentData =~ s/--//g;
1573 27 $ClosingTag =~ s/--//g;
1574  
1575 27 ▶ if (!$Self->{delete_defang_content}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($Self->{"delete_defang_content"}) 24 3 27
1576 # Put it all into the output
1577 24 $$OutR .= $StartTag
1578 . $CommentData
1579 . $ClosingTag
1580 . $CommentEndText
1581 . $CloseAngle;
1582 }
1583  
1584 # No closing comment, so we add that
1585 } else {
1586  
1587 6 ▶ $I =~ m/\G(.*)$/gcs || die "Remainder of line match failed";
Branch: 1 branch
BranchTrueFalseTotal
$I =~ /\G(.*)$/cgs or die "Remainder of line match failed" 6 0 6
1588
1589 6 my $Data = $1;
1590 6 $Data =~ s/--//g;
1591
1592 # Output
1593 6 ▶ if (!$Self->{delete_defang_content}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($Self->{"delete_defang_content"}) 6 0 6
1594 6 $$OutR .= $Data . $CommentEndText . ">";
1595 }
1596  
1597 }
1598  
1599 # XML processing instruction
1600 } elsif ($I =~ m{\G(\?)}gcs) {
1601 8 my ($Processing) = ($1);
1602 8 ▶ warn "defang XML processing instruction" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 8 8
1603
1604 8 my $Data;
1605 8 ▶ if ($I =~ m{\G(.*?\??)>}gcs) {
Branch: 1 branch
BranchTrueFalseTotal
if ($I =~ /\G(.*?\??)>/cgs) { } 6 2 8
1606 6 $Data = $1;
1607 } else {
1608 2 $I =~ m{\G(.*)$}gcs;
1609 2 $Data = $1;
1610 }
1611
1612 8 $Data =~ s{--}{}g;
1613  
1614 8 ▶ if (!$Self->{delete_defang_content}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($Self->{"delete_defang_content"}) 8 0 8
1615 8 $$OutR .= $OpenAngle . '!--' . $Processing . $Data . '-->';
1616 }
1617  
1618 }
1619 # Some other thing starting with <, keep looking
1620  
1621 1219 ▶ if (exists $Self->{TrackedAppendOutput}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $Self->{"TrackedAppendOutput"}) 3 1216 1219
1622 3 for (@{delete $Self->{TrackedAppendOutput}}) {
1623 3 $Self->open_tag(1, $OutR, \$I, $_->[0], \$_->[1], 1);
1624 }
1625 }
1626 1219 ▶ if (exists $Self->{AppendOutput}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $Self->{"AppendOutput"}) 152 1067 1219
1627 152 $$OutR .= delete $Self->{AppendOutput};
1628 }
1629 1219 ▶ if (exists $Self->{DelayedAppendOutput}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $Self->{"DelayedAppendOutput"}) 0 1219 1219
1630 0 $Self->defang(delete $Self->{DelayedAppendOutput}, { add_to_existing => 1 });
1631 }
1632 1219 next;
1633 }
1634
1635 # No tag found, just copy rest
1636 364 ▶ warn "defang OutputRemainder" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 364 364
1637 364 $I =~ m/\G(.*)$/gcs;
1638  
1639 364 ▶ $$OutR .= $1 if $1;
Branch: 1 branch
BranchTrueFalseTotal
if $1 313 51 364
1640  
1641 # Exit if we got here
1642 364 last;
1643 }
1644  
1645 # If not a recursive call, close mismatched tags
1646 364 ▶ if ($Self->{Reentrant}-- <= 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Self->{"Reentrant"}-- <= 1) 364 0 364
1647 364 $Self->close_all_tags($OutR, \$I);
1648 }
1649  
1650 # Turn on utf-8 flag again
1651 364 ▶ Encode::_utf8_on($$OutR) if $UTF8Input;
Branch: 1 branch
BranchTrueFalseTotal
if $UTF8Input 2 362 364
1652  
1653 364 return $$OutR;
1654 }
1655  
1656 =item I<extracted_styles()>
1657  
1658 With B<extract_styles> set, the defanged contents of the C<< <style> >>
1659 elements removed by the last call to C<defang>, ready to be put in a
1660 C<< <style> >> element of their own.
1661  
1662 =cut
1663 6 ▶sub extracted_styles {
Subroutine extracted_styles: called CC=1 SCAR=0.0
Pod documented
1664 6 my $Self = shift;
1665 6 return $Self->{extracted_styles};
1666 }
1667  
1668 =item I<add_to_output($String)>
1669  
1670 Appends $String to the output after the current parsed tag ends. Can be used by client code in callback methods to add HTML text to the processed output. If the HTML text needs to be defanged, client code can safely call HTML::Defang->defang() recursively from within the callback.
1671  
1672 =over 4
1673  
1674 =item B<Method parameters>
1675  
1676 =over 4
1677  
1678 =item I<$String>
1679  
1680 The string that is added after the current parsed tag ends.
1681  
1682 =back
1683  
1684 =back
1685  
1686 =back
1687  
1688 =cut
1689 154 ▶sub add_to_output {
Subroutine add_to_output: called CC=2 SCAR=6.9
Pod documented
1690 # Callbacks call this method
1691 154 my $Self = shift;
1692 154 ▶ $Self->{AppendOutput} = '' if !defined $Self->{AppendOutput};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $Self->{"AppendOutput"} 152 2 154
1693 154 $Self->{AppendOutput} .= shift;
1694 }
1695  
1696 0 ▶sub defang_and_add_to_output {
Subroutine defang_and_add_to_output: not called CC=2 SCAR=17.9
Pod undocumented
1697 0 my $Self = shift;
1698 0 ▶ $Self->{DelayedAppendOutput} = '' if !defined $Self->{DelayedAppendOutput};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $Self->{"DelayedAppendOutput"} 0 0 0
1699 0 $Self->{DelayedAppendOutput} .= shift;
1700 }
1701  
1702 3 ▶sub track_and_add_tag_to_output {
Subroutine track_and_add_tag_to_output: called CC=1 SCAR=0.0
Pod undocumented
1703 3 my $Self = shift;
1704 3 push @{$Self->{TrackedAppendOutput}}, shift;
1705 }
1706  
1707 =item B<INTERNAL METHODS>
1708  
1709 Generally these methods never need to be called by users of the class, because they'll be called internally as the appropriate tags are
1710 encountered, but they may be useful for some users in some cases.
1711  
1712 =over 4
1713  
1714 =cut
1715  
1716 =item I<defang_script_tag($OutR, $HtmlR, $TagOps, $OpenAngle, $IsEndTag, $Tag, $TagTrail, $Attributes, $CloseAngle)>
1717  
1718 This method is invoked when a <script> tag is parsed. Defangs the <script> opening tag, and any closing tag. Any scripting content is also commented out, so browsers don't display them.
1719  
1720 Returns 1 to indicate that the <script> tag must be defanged.
1721  
1722 =over 4
1723  
1724 =item B<Method parameters>
1725  
1726 =over 4
1727  
1728 =item I<$OutR>
1729  
1730 A reference to the processed output HTML before the tag that is currently being parsed.
1731  
1732 =item I<$HtmlR>
1733  
1734 A scalar reference to the input HTML.
1735  
1736 =item I<$TagOps>
1737  
1738 Indicates what operation should be done on a tag. Can be undefined, integer or code reference. Undefined indicates an unknown tag to HTML::Defang, 1 indicates a known safe tag, 0 indicates a known unsafe tag, and a code reference indicates a subroutine that should be called to parse the current tag. For example, <style> and <script> tags are parsed by dedicated subroutines.
1739  
1740 =item I<$OpenAngle>
1741  
1742 Opening angle(<) sign of the current tag.
1743  
1744 =item I<$IsEndTag>
1745  
1746 Has the value '/' if the current tag is a closing tag.
1747  
1748 =item I<$Tag>
1749  
1750 The HTML tag that is currently being parsed.
1751  
1752 =item I<$TagTrail>
1753  
1754 Any space after the tag, but before attributes.
1755  
1756 =item I<$Attributes>
1757  
1758 A reference to an array of the attributes and their values, including any surrouding spaces. Each element of the array is added by 'push' calls like below.
1759  
1760 push @$Attributes, [ $AttributeName, $SpaceBeforeEquals, $EqualsAndSubsequentSpace, $QuoteChar, $AttributeValue, $QuoteChar, $SpaceAfterAtributeValue ];
1761  
1762 =item I<$CloseAngle>
1763  
1764 Anything after the end of last attribute including the closing HTML angle(>)
1765  
1766 =back
1767  
1768 =back
1769  
1770 =cut
1771 53 ▶sub defang_script_tag {
Subroutine defang_script_tag: called CC=7 SCAR=19.5
Pod documented
1772 53 my $Self = shift;
1773 53 my ($OutR, $HtmlR, $TagOps, $OpenAngle, $IsEndTag, $lcTag, $TagTrail, $Attributes, $CloseAngle) = @_;
1774 53 ▶ warn "defang_script Processing <script> tag" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 53 53
1775  
1776 53 ▶ if (!$IsEndTag) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($IsEndTag) 27 26 53
1777  
1778 # If we just parsed a starting <script> tag, find up to end tag
1779 # There's all sort of possible mess around this:
1780 # </script<foo> - not really an end tag
1781 # </script foo="bar > yes, still in a attribute"> - a valid end tag
1782 # For weird cases, we end script tag early and end up defanging script
1783 # content as HTML content, which is still safe
1784 27 ▶ if ($$HtmlR =~ m{\G(.*?)(?=</script\b)}gcsi) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$HtmlR =~ m[\G(.*?)(?=</script\b)]cgis) 24 3 27
1785 24 my $ScriptTagContents = $1;
1786 24 ▶ warn "defang_script ScriptTagContents $ScriptTagContents" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 24 24
1787 24 ▶ if (!$Self->{delete_defang_content}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($Self->{"delete_defang_content"}) 23 1 24
1788 23 ▶ 1 while $ScriptTagContents =~ s/<!--|-->|--//g;
Branch: 1 branch
BranchTrueFalseTotal
$ScriptTagContents =~ s/<!--|-->|--//g and do { '???' } 4 23 27
1789 23 $ScriptTagContents = "<!-- " . $ScriptTagContents . " -->";
1790 23 $Self->add_to_output($ScriptTagContents);
1791 }
1792 }
1793 }
1794  
1795 # Also defang tag
1796 53 return DEFANG_ALWAYS;
1797 }
1798  
1799 =item I<defang_rcdata_content($HtmlR, $lcTag)>
1800  
1801 Consume the RCDATA/RAWTEXT content of a "text" element and pass it straight
1802 through to the output as opaque text.
1803  
1804 The elements this applies to are C<< <title> >> and C<< <textarea> >>
1805 (RCDATA) and C<< <noembed> >> and C<< <noframes> >> (RAWTEXT) - see the
1806 listing in C<%RawTextTags>. Per the HTML5 tree construction/tokenization
1807 spec, a start tag for one of these switches the tokenizer into a raw text
1808 mode in which the browser does I<not> parse comments or nested tags - the
1809 only markup it recognises is a matching C<< </tag >> end tag, everything
1810 else is text (RCDATA additionally decodes character references). Comments in
1811 particular are not a thing inside these elements.
1812  
1813 If we instead let the normal HTML parser loose on the content it would
1814 happily interpret C<< <!-- ... --> >> comments and nested tags inside. That
1815 diverges from the browser and is exploitable: an attacker can hide a literal
1816 end tag plus active markup inside what we think is an inert comment or
1817 attribute value, e.g.
1818  
1819 <title><!-- </title> <img src=x onerror=alert(1)> --></title>
1820  
1821 We would emit the C<< <img> >> unchanged (believing it comment data), but a
1822 browser closes the title at the literal C<< </title> >> and then runs the
1823 C<< <img> >> as live markup.
1824  
1825 So, like <script> and <style>, we consume everything up to the matching
1826 C<< </tag >> (whose name is C<$lcTag>) as opaque text. That content contains
1827 no C<< </tag >> (we stop before the first one), so re-parsed as raw text it
1828 stays inert right up to the end tag that follows it in the output.
1829  
1830 =cut
1831 12 ▶sub defang_rcdata_content {
Subroutine defang_rcdata_content: called CC=7 SCAR=21.1
Pod documented
1832 12 my ($Self, $HtmlR, $lcTag) = @_;
1833  
1834 12 ▶ warn "defang_rcdata_content Tag=$lcTag" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 12 12
1835  
1836 # Do the raw text scan in byte mode (see defang())
1837 11 ▶ use bytes;
Subroutine BEGIN: called CC=1 SCAR=0.0
1838  
1839 # Consume raw content verbatim up to the matching end tag (or EOF if
1840 # there's no closing tag, just as a browser would leave the element open)
1841 12 ▶ if ($$HtmlR =~ m{\G(.*?)(?=</\Q$lcTag\E\b)}gcis || $$HtmlR =~ m{\G(.*)$}gcs) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$HtmlR =~ m[\G(.*?)(?=</\Q$lcTag\E\b)]cgis or $$HtmlR =~ /\G(.*)$/cgs) 12 0 12
Condition66%2/3
$$HtmlR =~ m[\G(.*?)(?=</\Q$lcTag\E\b)]cgis or $$HtmlR =~ /\G(.*)$/cgs
l!l&&r!l&&!r
1110
MC/DC0%0/2
$$HtmlR =~ m[\G(.*?)(?=</\Q$lcTag\E\b)]cgis or $$HtmlR =~ /\G(.*)$/cgs
$$HtmlR =~ m[\G(.*?)(?=</\Q$lcTag\E\b)]cgis $$HtmlR =~ /\G(.*)$/cgs
Truth table66%2/3
A or B
A= $$HtmlR =~ m[\G(.*?)(?=</\Q$lcTag\E\b)]cgisB= $$HtmlR =~ /\G(.*)$/cgs
ABresult
1X1
011
000
1842 12 my $Content = $1;
1843 12 ▶ warn "defang_rcdata_content Content=$Content" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 12 12
1844 12 ▶ $Self->add_to_output($Content) if defined($Content) && length($Content);
Branch: 1 branch
BranchTrueFalseTotal
if defined $Content and length $Content 12 0 12
Condition33%1/3
defined $Content and length $Content
!ll&&!rl&&r
0012
MC/DC0%0/2
defined $Content and length $Content
defined $Content length $Content
Truth table33%1/3
A and B
A= defined $ContentB= length $Content
ABresult
0X0
100
111
1845 }
1846  
1847 12 return;
1848 }
1849  
1850 240 ▶sub defang_style_tag {
Subroutine defang_style_tag: called CC=20 SCAR=31.3
Pod undocumented
1851 240 my ($Self, $OutR, $HtmlR, $TagOps, $OpenAngle, $IsEndTag, $lcTag, $TagTrail, $Attributes, $CloseAngle) = @_;
1852  
1853 240 ▶ warn "defang_style_tag Tag=$lcTag IsEndTag=$IsEndTag" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 240 240
1854  
1855 240 my $Extract = $Self->{extract_styles};
1856 240 ▶ $Self->{SkipTagOutput} = 1 if $Extract;
Branch: 1 branch
BranchTrueFalseTotal
if $Extract 14 226 240
1857  
1858 # The media attribute isn't allowed on the tag, but is kept on extracted
1859 # styles as an @media block
1860 1 my ($Media) = map { $Self->cleanup_attribute($_->[4]) }
1861 240 ▶ grep { defined $_->[0] && lc $_->[0] eq 'media' && defined $_->[4] } @$Attributes;
Condition66%4/6
defined $_->[0] && lc $_->[0] eq 'media' && defined $_->[4]
!ll&&!rl&&r
301
defined $_->[0] and lc $_->[0] eq "media"
!ll&&!rl&&r
031
MC/DC33%1/3
defined $_->[0] && lc $_->[0] eq 'media' && defined $_->[4]
defined $_->[0] lc $_->[0] eq "media" defined $_->[4]
Truth table50%2/4
A and B && C
A= defined $_->[0]B= lc $_->[0] eq "media"C= defined $_->[4]
ABCresult
0XX0
10X0
1100
1111
1862  
1863 # Defang attributes
1864 240 my $Defang = $Self->defang_attributes($OutR, $HtmlR, $TagOps, $OpenAngle, $IsEndTag, $lcTag, $TagTrail, $Attributes, $CloseAngle);
1865  
1866 # Nothing to do if end tag
1867 240 ▶ return $Defang if $IsEndTag;
Branch: 1 branch
BranchTrueFalseTotal
if $IsEndTag 119 121 240
1868  
1869 # Do all style work in byte mode
1870 11 ▶ use bytes;
Subroutine BEGIN: called CC=1 SCAR=0.0
1871  
1872 121 my $Content = '';
1873 121 my $ClosingStyleTagPresent = 1;
1874  
1875 121 for ($$HtmlR) {
1876 121 ▶ if (m{\G(.*?)(?=</style\b)}gcis) {
Branch: 2 branches
BranchTrueFalseTotal
if (m[\G(.*?)(?=</style\b)]cgis) { } 119 2 121
elsif (/\G([^<]*)/cgis) { } 2 0 2
1877 119 $Content = $1;
1878  
1879 # No ending style tag
1880 } elsif (m{\G([^<]*)}gcis) {
1881 2 $Content = $1;
1882 2 $ClosingStyleTagPresent = 0;
1883 }
1884 }
1885  
1886 # Handle any wrapping HTML comments. If no comments, we add
1887 121 my ($OpeningHtmlComment, $ClosingHtmlComment) = ('', '');
1888 121 ▶ $OpeningHtmlComment = $Content =~ s{^(\s*<!--)}{} ? $1 . " " : "<!-- ";
Branch: 1 branch
BranchTrueFalseTotal
$Content =~ s/^(\s*<!--)// ? : 4 117 121
1889 121 ▶ $ClosingHtmlComment = $Content =~ s{(-->\s*)$}{} ? " " . $1 : " -->";
Branch: 1 branch
BranchTrueFalseTotal
$Content =~ s/(-->\s*)$// ? : 4 117 121
1890  
1891 # Check for large bogus style data with mostly HTML tags and blat it
1892 121 ▶ if (length $Content > 16384) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $Content > 16384) 0 121 121
1893 0 my $TagCount = 0;
1894 0 ▶ $TagCount++ while $Content =~ m{</?\w+\b[^>]*>}g;
Branch: 1 branch
BranchTrueFalseTotal
$Content =~ m[</?\w+\b[^>]*>]g and do { ++$TagCount } 0 0 0
1895 0 ▶ if ($TagCount > length($Content)/256) {
Branch: 1 branch
BranchTrueFalseTotal
if ($TagCount > length($Content) / 256) 0 0 0
1896 0 $Content = '';
1897 }
1898 }
1899  
1900 121 my $StyleOut = $Self->defang_style_text($Content, $lcTag, 0, undef, $HtmlR, $OutR);
1901  
1902 121 ▶ if ($Extract) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Extract) 7 114 121
1903 7 ▶ return $Defang if $StyleOut !~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
unless $StyleOut =~ /\S/ 1 6 7
1904 $StyleOut = "\@media $Media {\n$StyleOut\n}"
1905 6 ▶ if defined $Media && $Media =~ $Rules{media} && $Media !~ /^\s*all\s*$/i;
Branch: 1 branch
BranchTrueFalseTotal
if defined $Media and $Media =~ /$Rules{"media"}/ and not $Media =~ /^\s*all\s*$/i 1 5 6
Condition66%4/6
defined $Media and $Media =~ /$Rules{"media"}/ and not $Media =~ /^\s*all\s*$/i
!ll&&!rl&&r
501
defined $Media and $Media =~ /$Rules{"media"}/
!ll&&!rl&&r
501
MC/DC33%1/3
defined $Media and $Media =~ /$Rules{"media"}/ and not $Media =~ /^\s*all\s*$/i
defined $Media $Media =~ /$Rules{"media"}/ not $Media =~ /^\s*all\s*$/i
Truth table50%2/4
A and B and not(C)
A= defined $MediaB= $Media =~ /$Rules{"media"}/C= not $Media =~ /^\s*all\s*$/i
ABCresult
0XX0
10X0
1100
1111
1906 # Make sure nothing can end the <style> element it's put into
1907 6 $StyleOut =~ s{</}{<\\/}g;
1908 6 $Self->{extracted_styles} .= "$StyleOut\n";
1909 6 return $Defang;
1910 }
1911  
1912 114 $Self->add_to_output($OpeningHtmlComment . $StyleOut . $ClosingHtmlComment);
1913 114 ▶ $Self->add_to_output("</style>") if !$ClosingStyleTagPresent;
Branch: 1 branch
BranchTrueFalseTotal
unless $ClosingStyleTagPresent 2 112 114
1914  
1915 114 return $Defang;
1916 }
1917  
1918 =item I<defang_style_text($Content, $lcTag, $IsAttr, $AttributeHash, $HtmlR, $OutR)>
1919  
1920 Defang some raw css data and return the defanged content
1921  
1922 =over 4
1923  
1924 =item B<Method parameters>
1925  
1926 =over 4
1927  
1928 =item I<$Content>
1929  
1930 The input style string that is defanged.
1931  
1932 =item I<$IsAttr>
1933  
1934 True if $Content is from an attribute, otherwise from a <style> block
1935  
1936 =back
1937  
1938 =back
1939  
1940 =cut
1941 331 ▶sub defang_style_text {
Subroutine defang_style_text: called CC=36 SCAR=37.9
Pod documented
1942 331 my ($Self, $Content, $lcTag, $IsAttr, $AttributeHash, $HtmlR, $OutR) = @_;
1943  
1944 # Clean up all comments, expand character escapes and such
1945 331 $Self->cleanup_style($Content, $IsAttr);
1946  
1947 # Style attributes can optionally have selector type elements, so we check whether we
1948 # have a '{' in $Content: if yes, its style data with selector type elements
1949 331 my $Naked = $Content !~ m/\{/;
1950 331 ▶ warn "defang_style Naked=$Naked" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 331 331
1951  
1952 # And suitably change the regex to match the data
1953 331 ▶ my $SelectorRuleRE = $Naked ? $RECStyleNaked : $RECStyleSelected;
Branch: 1 branch
BranchTrueFalseTotal
$Naked ? : 144 187 331
1954  
1955 331 my (@Selectors, @SelectorRules, @ExtraData, @InMedia);
1956  
1957 # Now we parse the selectors and declarations
1958 331 while (1) {
1959 753 ▶ if ($Content =~ m{$RECStyleMediaSelector}sgco) {
Branch: 7 branches
BranchTrueFalseTotal
if ($Content =~ /$RECStyleMediaSelector/cogs) { } 4 749 753
elsif (@InMedia and $Content =~ /\G(\s*)(\})(\s*)/cgs) { } 4 745 749
elsif ($Content =~ /$SelectorRuleRE/cgs) { } 556 189 745
elsif (not $Naked and $Content =~ /\G\s*$StyleSelectors\s*$/cgs) { } 2 187 189
elsif (not $Naked and $Content =~ m[\G(?:</?$TagNameRE(?:\s[^>\{\}]*)?>\s*)+]cgs) { } 0 187 187
elsif ($Content =~ /\G\s+/cgs) { } 0 187 187
elsif ($Content =~ /\G[^\s<]+/cgs or $Content =~ /\G<+/cgs) { } 0 187 187
1960 4 push @InMedia, $2;
1961 4 push @Selectors, $2;
1962 4 push @SelectorRules, "";
1963 4 push @ExtraData, [ $1, "", $3, "", $4 ];
1964 ▶ } elsif (@InMedia && $Content =~ m{\G(\s*)(\})(\s*)}sgc) {
Condition100%3/3
@InMedia and $Content =~ /\G(\s*)(\})(\s*)/cgs
!ll&&!rl&&r
74144
MC/DC100%2/2
@InMedia and $Content =~ /\G(\s*)(\})(\s*)/cgs
@InMedia $Content =~ /\G(\s*)(\})(\s*)/cgs
Truth table100%3/3
A and B
A= @InMediaB= $Content =~ /\G(\s*)(\})(\s*)/cgs
ABresult
0X0
100
111
1965 4 pop @InMedia;
1966 4 push @Selectors, "";
1967 4 push @SelectorRules, "";
1968 4 push @ExtraData, [ $1, "", "", $2, $3 ];
1969 } elsif ($Content =~ m{$SelectorRuleRE}sgc) {
1970 556 my ($Selector, $SelectorRule) = ($2, $5);
1971 556 ▶ last if $Selector eq '' && $SelectorRule =~ /^[;\s]*$/;
Branch: 1 branch
BranchTrueFalseTotal
if $Selector eq "" and $SelectorRule =~ /^[;\s]*$/ 144 412 556
Condition100%3/3
$Selector eq "" and $SelectorRule =~ /^[;\s]*$/
!ll&&!rl&&r
274138144
MC/DC100%2/2
$Selector eq "" and $SelectorRule =~ /^[;\s]*$/
$Selector eq "" $SelectorRule =~ /^[;\s]*$/
Truth table100%3/3
A and B
A= $Selector eq ""B= $SelectorRule =~ /^[;\s]*$/
ABresult
0X0
100
111
1972 412 ▶ $Selector = join("\000", @InMedia, $Selector) if @InMedia;
Branch: 1 branch
BranchTrueFalseTotal
if @InMedia 4 408 412
1973 412 push @Selectors, $Selector;
1974 412 push @SelectorRules, $SelectorRule;
1975 412 push @ExtraData, [ $1, $3, $4, $6, $7];
1976 412 ▶ warn "defang_style Selector=$Selector" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 412 412
1977 412 ▶ warn "defang_style SelectorRule=$SelectorRule" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 412 412
1978  
1979 # Just a large bunch of selectors and no rules, suck up and discard
1980 ▶ } elsif (!$Naked && $Content =~ m{\G\s*$StyleSelectors\s*$}sgc) {
Condition66%2/3
not $Naked and $Content =~ /\G\s*$StyleSelectors\s*$/cgs
!ll&&!rl&&r
01872
MC/DC50%1/2
not $Naked and $Content =~ /\G\s*$StyleSelectors\s*$/cgs
not $Naked $Content =~ /\G\s*$StyleSelectors\s*$/cgs
Truth table66%2/3
not(A) and B
A= not $NakedB= $Content =~ /\G\s*$StyleSelectors\s*$/cgs
ABresult
0X0
100
111
1981 # Looks like an html tag, suck up and discard
1982 ▶ } elsif (!$Naked && $Content =~ m{\G(?:</?$TagNameRE(?:\s[^>\{\}]*)?>\s*)+}sgc) {
Condition33%1/3
not $Naked and $Content =~ m[\G(?:</?$TagNameRE(?:\s[^>\{\}]*)?>\s*)+]cgs
!ll&&!rl&&r
01870
MC/DC0%0/2
not $Naked and $Content =~ m[\G(?:</?$TagNameRE(?:\s[^>\{\}]*)?>\s*)+]cgs
not $Naked $Content =~ m[\G(?:</?$TagNameRE(?:\s[^>\{\}]*)?>\s*)+]cgs
Truth table33%1/3
not(A) and B
A= not $NakedB= $Content =~ m[\G(?:</?$TagNameRE(?:\s[^>\{\}]*)?>\s*)+]cgs
ABresult
0X0
100
111
1983  
1984 # If content didn't match a rule, suck up whitespace
1985 } elsif ($Content =~ m{\G\s+}sgc) {
1986 # Or any non-whitespace, but try and sync to <...> tags
1987 ▶ } elsif ($Content =~ m{\G[^\s<]+}sgc || $Content =~ m{\G<+}sgc) {
Condition33%1/3
$Content =~ /\G[^\s<]+/cgs or $Content =~ /\G<+/cgs
l!l&&r!l&&!r
00187
MC/DC0%0/2
$Content =~ /\G[^\s<]+/cgs or $Content =~ /\G<+/cgs
$Content =~ /\G[^\s<]+/cgs $Content =~ /\G<+/cgs
Truth table33%1/3
A or B
A= $Content =~ /\G[^\s<]+/cgsB= $Content =~ /\G<+/cgs
ABresult
1X1
011
000
1988  
1989 # Nothing matched, must be at end
1990 187 } else { last; }
1991 }
1992  
1993 # Check declaration elements for defanging
1994 331 $Self->defang_stylerule(\@Selectors, \@SelectorRules, $lcTag, $IsAttr, $AttributeHash, $HtmlR, $OutR);
1995  
1996 # An undef selector drops its rule from the output below
1997 331 ▶ if (defined $Self->{scope_id} && !$IsAttr) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $Self->{"scope_id"} and not $IsAttr) 2 329 331
Condition100%3/3
defined $Self->{"scope_id"} and not $IsAttr
!ll&&!rl&&r
32722
MC/DC100%2/2
defined $Self->{"scope_id"} and not $IsAttr
defined $Self->{"scope_id"} not $IsAttr
Truth table100%3/3
A and not(B)
A= defined $Self->{"scope_id"}B= not $IsAttr
ABresult
0X0
100
111
1998 2 $_ = $Self->scope_selector($_) for @Selectors;
1999 }
2000  
2001 331 my $StyleOut = "";
2002  
2003 # Re-create the style data
2004 331 foreach my $Selector (@Selectors) {
2005  
2006 420 my $SelectorRule = shift @SelectorRules;
2007 420 my $Spaces = shift @ExtraData;
2008 420 ▶ my ($BeforeSelector, $AfterSelector, $OpenBrace, $CloseBrace, $AfterRule) = @$Spaces if $Spaces;
Branch: 1 branch
BranchTrueFalseTotal
if $Spaces 420 0 420
2009 420 ▶ ($BeforeSelector, $AfterSelector, $AfterRule) = ("", " ", "\n") unless $Spaces;
Branch: 1 branch
BranchTrueFalseTotal
unless $Spaces 0 420 420
2010 420 ▶ ($OpenBrace, $CloseBrace) = ("{", "}") if !$Spaces && !$IsAttr;
Branch: 1 branch
BranchTrueFalseTotal
unless $Spaces or $IsAttr 0 420 420
Condition33%1/3
$Spaces or $IsAttr
l!l&&r!l&&!r
42000
MC/DC0%0/2
$Spaces or $IsAttr
$Spaces $IsAttr
Truth table33%1/3
A or B
A= $SpacesB= $IsAttr
ABresult
1X1
011
000
2011
2012 # Put back the rule together
2013 420 ▶ if (defined($Selector)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $Selector) 419 1 420
2014 419 ▶ $StyleOut .= $BeforeSelector if defined($BeforeSelector);
Branch: 1 branch
BranchTrueFalseTotal
if defined $BeforeSelector 419 0 419
2015 419 ▶ $StyleOut .= $Selector =~ /\000/ ? (reverse split /\000/, $Selector)[0] : $Selector;
Branch: 1 branch
BranchTrueFalseTotal
$Selector =~ /\000/ ? : 4 415 419
2016 419 ▶ $StyleOut .= $AfterSelector if defined($AfterSelector);
Branch: 1 branch
BranchTrueFalseTotal
if defined $AfterSelector 419 0 419
2017 419 ▶ $StyleOut .= $OpenBrace if defined($OpenBrace);
Branch: 1 branch
BranchTrueFalseTotal
if defined $OpenBrace 419 0 419
2018 419 ▶ $StyleOut .= $SelectorRule if defined($SelectorRule);
Branch: 1 branch
BranchTrueFalseTotal
if defined $SelectorRule 376 43 419
2019 419 ▶ $StyleOut .= $CloseBrace if defined($CloseBrace);
Branch: 1 branch
BranchTrueFalseTotal
if defined $CloseBrace 419 0 419
2020 419 ▶ $StyleOut .= $AfterRule if defined($AfterRule);
Branch: 1 branch
BranchTrueFalseTotal
if defined $AfterRule 419 0 419
2021 }
2022
2023 }
2024  
2025 331 ▶ warn "defang_style StyleOut=$StyleOut" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 331 331
2026  
2027 331 return $StyleOut;
2028 }
2029  
2030 =item I<scope_selector($Selector)>
2031  
2032 With B<scope_id> set, scope a selector (or comma separated list of them)
2033 from a C<< <style> >> as described there, in the form given to
2034 B<css_callback>. Returns undef if no part of it could match inside the
2035 scope element, so the rule should be dropped.
2036  
2037 =cut
2038 12 ▶sub scope_selector {
Subroutine scope_selector: called CC=5 SCAR=16.1
Pod documented
2039 12 my ($Self, $Selector) = @_;
2040 11 ▶ use bytes;
Subroutine BEGIN: called CC=1 SCAR=0.0
2041  
2042 12 ▶ return $Selector if !defined $Selector || $Selector !~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $Selector and $Selector =~ /\S/ 1 11 12
Condition66%2/3
defined $Selector and $Selector =~ /\S/
!ll&&!rl&&r
0111
MC/DC50%1/2
defined $Selector and $Selector =~ /\S/
defined $Selector $Selector =~ /\S/
Truth table66%2/3
A and B
A= defined $SelectorB= $Selector =~ /\S/
ABresult
0X0
100
111
2043  
2044 # Only the part after any @media prelude is a selector, and at-rules
2045 # (@media, @font-face, @page) aren't
2046 11 my @Parts = split /\0/, $Selector, -1;
2047 11 ▶ return $Selector if $Parts[-1] =~ /^\s*\@/;
Branch: 1 branch
BranchTrueFalseTotal
if $Parts[-1] =~ /^\s*\@/ 2 9 11
2048  
2049 9 my @Scoped = grep { defined } map { $Self->scope_complex_selector($_) }
2050 split_selector_list($Parts[-1]);
2051 9 ▶ return undef if !@Scoped;
Branch: 1 branch
BranchTrueFalseTotal
unless @Scoped 1 8 9
2052  
2053 8 $Parts[-1] = join ", ", @Scoped;
2054 8 return join "\0", @Parts;
2055 }
2056  
2057 # Split a selector list on the commas between selectors, not those inside
2058 # parentheses, attribute selectors, strings or escapes
2059 9 ▶sub split_selector_list {
Subroutine split_selector_list: called CC=9 SCAR=22.0
Pod undocumented
2060 9 my ($List) = @_;
2061 11 ▶ use bytes;
Subroutine BEGIN: called CC=1 SCAR=0.0
2062  
2063 9 my (@Selectors, $Depth);
2064 9 my $Current = '';
2065 9 $Depth = 0;
2066 9 ▶ while ($List =~ m{\G(\\.|"(?:[^"\\]|\\.)*"?|'(?:[^'\\]|\\.)*'?|[^\\"'()\[\],]+|.)}gcs) {
Branch: 1 branch
BranchTrueFalseTotal
if ($List =~ /\G(\\.|"(?:[^"\\]|\\.)*"?|'(?:[^'\\]|\\.)*'?|[^\\"'()\[\],]+|.)/cgs) 44 9 53
2067 44 my $Token = $1;
2068 44 ▶ if ($Token eq ',' && !$Depth) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Token eq "," and not $Depth) 9 35 44
Condition66%2/3
$Token eq "," and not $Depth
!ll&&!rl&&r
3509
MC/DC50%1/2
$Token eq "," and not $Depth
$Token eq "," not $Depth
Truth table66%2/3
A and not(B)
A= $Token eq ","B= not $Depth
ABresult
0X0
100
111
2069 9 push @Selectors, $Current;
2070 9 $Current = '';
2071 9 next;
2072 }
2073 35 ▶ $Depth++ if $Token eq '(' || $Token eq '[';
Branch: 1 branch
BranchTrueFalseTotal
if $Token eq "(" or $Token eq "[" 5 30 35
Condition100%3/3
$Token eq "(" or $Token eq "["
l!l&&r!l&&!r
1430
MC/DC100%2/2
$Token eq "(" or $Token eq "["
$Token eq "(" $Token eq "["
Truth table100%3/3
A or B
A= $Token eq "("B= $Token eq "["
ABresult
1X1
011
000
2074 35 ▶ $Depth-- if ($Token eq ')' || $Token eq ']') && $Depth;
Branch: 1 branch
BranchTrueFalseTotal
if $Token eq ")" || $Token eq "]" and $Depth 5 30 35
Condition83%5/6
$Token eq ")" || $Token eq "]" and $Depth
!ll&&!rl&&r
3005
$Token eq ")" or $Token eq "]"
l!l&&r!l&&!r
1430
MC/DC66%2/3
$Token eq ")" || $Token eq "]" and $Depth
$Token eq ")" $Token eq "]" $Depth
Truth table60%3/5
A or B and C
A= $Token eq ")"B= $Token eq "]"C= $Depth
ABCresult
00X0
1X00
0100
1X11
0111
2075 35 $Current .= $Token;
2076 }
2077 9 push @Selectors, $Current;
2078  
2079 9 return @Selectors;
2080 }
2081  
2082 18 ▶sub scope_complex_selector {
Subroutine scope_complex_selector: called CC=12 SCAR=24.9
Pod undocumented
2083 18 my ($Self, $Selector) = @_;
2084 11 ▶ use bytes;
Subroutine BEGIN: called CC=1 SCAR=0.0
2085  
2086 18 $Selector =~ s/^\s+//;
2087 18 $Selector =~ s/\s+$//;
2088 18 ▶ return undef if $Selector eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $Selector eq "" 0 18 18
2089  
2090 # The scope element stands in for the document's root and body, so
2091 # "body > p" is "#qt > p", and "body.x" is "#qt.qt-x"
2092 18 my $OnScope = 0;
2093 18 ▶ while ($Selector =~ s/^(?:html|body|:root)(?![\w-])(\s*)//i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Selector =~ s/^(?:html|body|:root)(?![\w-])(\s*)//i) 9 18 27
2094 9 $OnScope = !length $1;
2095 9 $Selector =~ s/^>\s*(?=(?:html|body|:root)(?![\w-]))//i;
2096 }
2097 # The scope element's siblings aren't the document's
2098 18 ▶ return undef if $Selector =~ /^[~+]/;
Branch: 1 branch
BranchTrueFalseTotal
if $Selector =~ /^[~+]/ 2 16 18
2099 16 ▶ $OnScope = 0 if $Selector eq '' || $Selector =~ /^[>\s]/;
Branch: 1 branch
BranchTrueFalseTotal
if $Selector eq "" or $Selector =~ /^[>\s]/ 4 12 16
Condition100%3/3
$Selector eq "" or $Selector =~ /^[>\s]/
l!l&&r!l&&!r
3112
MC/DC100%2/2
$Selector eq "" or $Selector =~ /^[>\s]/
$Selector eq "" $Selector =~ /^[>\s]/
Truth table100%3/3
A or B
A= $Selector eq ""B= $Selector =~ /^[>\s]/
ABresult
1X1
011
000
2100  
2101 # "* p" is just any p inside
2102 16 $Selector =~ s/^\*\s+(?=[^\s>+~])//;
2103  
2104 16 my $Prefix = "$Self->{scope_id}-";
2105 16 my $Out = '';
2106 16 ▶ while ($Selector =~ m{\G(?:(\\.|"(?:[^"\\]|\\.)*"?|'(?:[^'\\]|\\.)*'?)|(\[(?:[^\]"'\\]|\\.|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')*\]?)|([#.])(?=[A-Za-z_\x80-\xff\\-])|([^\\"'\[#.]+|.))}gcs) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Selector =~ /\G(?:(\\.|"(?:[^"\\]|\\.)*"?|'(?:[^'\\]|\\.)*'?)|(\[(?:[^\]"'\\]|\\.|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')*\]?)|([#.])(?=[A-Za-z_\x80-\xff\\-])|([^\\"'\[#.]+|.))/cgs) 25 16 41
2107 25 ▶ if (defined $2) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $2) { } 4 21 25
elsif (defined $3) { } 8 13 21
2108 4 $Out .= scope_attribute_selector($2, $Prefix);
2109 } elsif (defined $3) {
2110 8 $Out .= $3 . $Prefix;
2111 } else {
2112 13 ▶ $Out .= defined $1 ? $1 : $4;
Branch: 1 branch
BranchTrueFalseTotal
defined $1 ? : 0 13 13
2113 }
2114 }
2115  
2116 16 my $Scope = "#$Self->{scope_id}";
2117 16 ▶ return $Out eq '' ? $Scope : $OnScope ? "$Scope$Out" : "$Scope $Out";
Branch: 2 branches
BranchTrueFalseTotal
$Out eq '' ? : 3 13 16
$OnScope ? : 1 12 13
2118 }
2119  
2120 # Prefix the value in an [id=...], [class~=...] or [for=...] selector the
2121 # same way as the attribute it matches. Matching the end or middle of one
2122 # doesn't need it, except for the words after a space in a class.
2123 4 ▶sub scope_attribute_selector {
Subroutine scope_attribute_selector: called CC=11 SCAR=24.4
Pod undocumented
2124 4 my ($AttributeSelector, $Prefix) = @_;
2125  
2126 4 ▶ $AttributeSelector =~ m{^\[\s*(id|class|for)\s*([~|^\$*]?=)\s*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|([^\s\]"']+))\s*([is]?)\s*\]$}is
Branch: 1 branch
BranchTrueFalseTotal
$AttributeSelector =~ /^\[\s*(id|class|for)\s*([~|^\$*]?=)\s*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|([^\s\]"']+))\s*([is]?)\s*\]$/is or return $AttributeSelector 3 1 4
2127 or return $AttributeSelector;
2128  
2129 3 my ($Name, $Operator, $Flag) = ($1, $2, $6);
2130 3 ▶ my $Quote = defined $4 ? "'" : '"';
Branch: 1 branch
BranchTrueFalseTotal
defined $4 ? : 0 3 3
2131 3 ▶ my $Value = defined $3 ? $3 : defined $4 ? $4 : $5;
Branch: 2 branches
BranchTrueFalseTotal
defined $3 ? : 1 2 3
defined $4 ? : 0 2 2
2132 3 ▶ my $FromStart = $Operator ne '$=' && $Operator ne '*=';
Condition66%2/3
$Operator ne '$=' && $Operator ne '*='
!ll&&!rl&&r
012
MC/DC50%1/2
$Operator ne '$=' && $Operator ne '*='
$Operator ne '$=' $Operator ne '*='
Truth table66%2/3
A && B
A= $Operator ne '$='B= $Operator ne '*='
ABresult
0X0
100
111
2133  
2134 3 ▶ if (lc $Name eq 'class') {
Branch: 2 branches
BranchTrueFalseTotal
if (lc $Name eq 'class') { } 2 1 3
elsif ($FromStart) { } 1 0 1
2135 2 ▶ $Value =~ s/(^|\s+)(?=\S)/length $1 || $FromStart ? "$1$Prefix" : ''/ge;
Branch: 1 branch
BranchTrueFalseTotal
length $1 || $FromStart ? : 2 1 3
Condition100%3/3
length $1 or $FromStart
l!l&&r!l&&!r
111
MC/DC100%2/2
length $1 or $FromStart
length $1 $FromStart
Truth table100%3/3
A or B
A= length $1B= $FromStart
ABresult
1X1
011
000
2136 } elsif ($FromStart) {
2137 1 $Value = $Prefix . $Value;
2138 }
2139  
2140 3 ▶ return "[$Name$Operator$Quote$Value$Quote" . ($Flag ? " $Flag" : '') . "]";
Branch: 1 branch
BranchTrueFalseTotal
$Flag ? : 0 3 3
2141 }
2142  
2143 =item I<scope_attribute($lcTag, $lcAttrKey, $AttrValR)>
2144  
2145 With B<scope_id> set, prefix an id, class or reference to one in an
2146 attribute value to match scoped selectors.
2147  
2148 =cut
2149 16 ▶sub scope_attribute {
Subroutine scope_attribute: called CC=10 SCAR=23.1
Pod documented
2150 16 my ($Self, $lcTag, $lcAttrKey, $AttrValR) = @_;
2151  
2152 16 my $Prefix = "$Self->{scope_id}-";
2153  
2154 16 ▶ if ($lcAttrKey eq 'id' || $lcAttrKey eq 'for'
Branch: 3 branches
BranchTrueFalseTotal
if ($lcAttrKey eq 'id' or $lcAttrKey eq 'for' or $lcAttrKey eq 'name' and $lcTag eq 'a' || $lcTag eq 'map') { } 4 12 16
elsif ($lcAttrKey eq 'class' or $lcAttrKey eq 'headers') { } 2 10 12
elsif ($lcAttrKey eq 'href' or $lcAttrKey eq 'usemap') { } 5 5 10
Condition83%10/12
$lcAttrKey eq "id" or $lcAttrKey eq "for" or $lcAttrKey eq "name" and $lcTag eq "a" || $lcTag eq "map"
l!l&&r!l&&!r
2212
$lcAttrKey eq "id" or $lcAttrKey eq "for"
l!l&&r!l&&!r
1114
$lcAttrKey eq "name" and $lcTag eq "a" || $lcTag eq "map"
!ll&&!rl&&r
1202
$lcTag eq "a" or $lcTag eq "map"
l!l&&r!l&&!r
110
MC/DC60%3/5
$lcAttrKey eq "id" or $lcAttrKey eq "for" or $lcAttrKey eq "name" and $lcTag eq "a" || $lcTag eq "map"
$lcAttrKey eq "id" $lcAttrKey eq "for" $lcAttrKey eq "name" $lcTag eq "a" $lcTag eq "map"
Truth table83%5/6
A or B or C and D or E
A= $lcAttrKey eq "id"B= $lcAttrKey eq "for"C= $lcAttrKey eq "name"D= $lcTag eq "a"E= $lcTag eq "map"
ABCDEresult
1XXXX1
01XXX1
0011X1
001011
000XX0
001000
2155 || ($lcAttrKey eq 'name' && ($lcTag eq 'a' || $lcTag eq 'map'))) {
2156 4 $$AttrValR =~ s/^(\s*)(?=\S)/$1$Prefix/;
2157 ▶ } elsif ($lcAttrKey eq 'class' || $lcAttrKey eq 'headers') {
Condition66%2/3
$lcAttrKey eq "class" or $lcAttrKey eq "headers"
l!l&&r!l&&!r
2010
MC/DC50%1/2
$lcAttrKey eq "class" or $lcAttrKey eq "headers"
$lcAttrKey eq "class" $lcAttrKey eq "headers"
Truth table66%2/3
A or B
A= $lcAttrKey eq "class"B= $lcAttrKey eq "headers"
ABresult
1X1
011
000
2158 2 $$AttrValR =~ s/(^|\s+)(?=\S)/$1$Prefix/g;
2159 ▶ } elsif ($lcAttrKey eq 'href' || $lcAttrKey eq 'usemap') {
Condition100%3/3
$lcAttrKey eq "href" or $lcAttrKey eq "usemap"
l!l&&r!l&&!r
415
MC/DC100%2/2
$lcAttrKey eq "href" or $lcAttrKey eq "usemap"
$lcAttrKey eq "href" $lcAttrKey eq "usemap"
Truth table100%3/3
A or B
A= $lcAttrKey eq "href"B= $lcAttrKey eq "usemap"
ABresult
1X1
011
000
2160 5 $$AttrValR =~ s/^(\s*#)(?=\S)/$1$Prefix/;
2161 }
2162 }
2163  
2164 =item I<cleanup_style($StyleString)>
2165  
2166 Helper function to clean up CSS data. This function directly operates on the input string without taking a copy.
2167  
2168 =over 4
2169  
2170 =item B<Method parameters>
2171  
2172 =over 4
2173  
2174 =item I<$StyleString>
2175  
2176 The input style string that is cleaned.
2177  
2178 =back
2179  
2180 =back
2181  
2182 =cut
2183 331 ▶sub cleanup_style {
Subroutine cleanup_style: called CC=26 SCAR=42.1
Pod documented
2184 331 my $Self = shift;
2185
2186 331 for ($_[0]) {
2187 331 my $UnicodeEntity = 0;
2188 # Expand unicode \ refs
2189 331 s{(?:\\)(0?[\da-f]{1,6});?}{
2190 31 ▶ my $V = (defined($1) && hex($1)) || undef;
Condition40%2/5
defined $1 && hex $1 || undef
l!l
310
defined $1 and hex $1
!ll&&!rl&&r
0031
MC/DC0%0/2
defined $1 && hex $1 || undef
defined $1 hex $1
Truth table33%1/3
A and B
A= defined $1B= hex $1
ABresult
111
0X0
100
2191 31 ▶ $UnicodeEntity = 1 if $V && $V > 127;
Branch: 1 branch
BranchTrueFalseTotal
if $V and $V > 127 0 31 31
Condition33%1/3
$V and $V > 127
!ll&&!rl&&r
0310
MC/DC0%0/2
$V and $V > 127
$V $V > 127
Truth table33%1/3
A and B
A= $VB= $V > 127
ABresult
0X0
100
111
2192 31 ▶ $V && $V < 1_114_111 && $V != 65535 && !($V > 55295 && $V < 57344) ? chr($V) : ""
Branch: 1 branch
BranchTrueFalseTotal
$V && $V < 1114111 && $V != 65535 && !($V > 55295 && $V < 57344) ? : 31 0 31
Condition33%4/12
$V and $V < 1114111 and $V != 65535 and not $V > 55295 && $V < 57344
!ll&&!rl&&r
0031
$V and $V < 1114111 and $V != 65535
!ll&&!rl&&r
0031
$V and $V < 1114111
!ll&&!rl&&r
0031
$V > 55295 && $V < 57344
!ll&&!rl&&r
3100
MC/DC0%0/5
$V and $V < 1114111 and $V != 65535 and not $V > 55295 && $V < 57344
$V $V < 1114111 $V != 65535 $V > 55295 $V < 57344
Truth table16%1/6
A and B and C and not(D && E)
A= $VB= $V < 1114111C= $V != 65535D= $V > 55295E= $V < 57344
ABCDEresult
0XXXX0
10XXX0
110XX0
111110
1110X1
111101
2193 }egi;
2194 # Remove all remaining invalid escapes TODO This probably is not correct. Backslashes are required to be left alone by the CSS syntax
2195 331 s/\\//g;
2196  
2197 # Second param is true if it's an attribute, which means these have already been done
2198 331 ▶ if (!$_[1]) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($_[1]) 121 210 331
2199 # Expand escapes
2200 121 s{&#(?:x(0?[\da-f]{1,6})|([\d]{1,7}));?}{
2201 126 ▶ my $V = (defined($1) && hex($1)) || (defined($2) && int($2)) || undef;
Condition54%6/11
defined $1 && hex $1 || defined $2 && int $2 || undef
l!l
1260
defined $1 and hex $1 or defined $2 and int $2
l!l&&r!l&&!r
11250
defined $1 and hex $1
!ll&&!rl&&r
12501
defined $2 and int $2
!ll&&!rl&&r
00125
MC/DC0%0/4
defined $1 && hex $1 || defined $2 && int $2 || undef
defined $1 hex $1 defined $2 int $2
Truth table28%2/7
A and B or C and D
A= defined $1B= hex $1C= defined $2D= int $2
ABCDresult
11XX1
0X111
10111
0X0X0
0X100
100X0
10100
2202 126 ▶ $UnicodeEntity = 1 if $V && $V > 127;
Branch: 1 branch
BranchTrueFalseTotal
if $V and $V > 127 1 125 126
Condition66%2/3
$V and $V > 127
!ll&&!rl&&r
01251
MC/DC50%1/2
$V and $V > 127
$V $V > 127
Truth table66%2/3
A and B
A= $VB= $V > 127
ABresult
0X0
100
111
2203 126 ▶ $V && $V < 1_114_111 && $V != 65535 && !($V > 55295 && $V < 57344) ? chr($V) : "";
Branch: 1 branch
BranchTrueFalseTotal
$V && $V < 1114111 && $V != 65535 && !($V > 55295 && $V < 57344) ? : 126 0 126
Condition33%4/12
$V and $V < 1114111 and $V != 65535 and not $V > 55295 && $V < 57344
!ll&&!rl&&r
00126
$V and $V < 1114111 and $V != 65535
!ll&&!rl&&r
00126
$V and $V < 1114111
!ll&&!rl&&r
00126
$V > 55295 && $V < 57344
!ll&&!rl&&r
12600
MC/DC0%0/5
$V and $V < 1114111 and $V != 65535 and not $V > 55295 && $V < 57344
$V $V < 1114111 $V != 65535 $V > 55295 $V < 57344
Truth table16%1/6
A and B and C and not(D && E)
A= $VB= $V < 1114111C= $V != 65535D= $V > 55295E= $V < 57344
ABCDEresult
0XXXX0
10XXX0
110XX0
111110
1110X1
111101
2204 }egi;
2205 121 ▶ s/&(quot|apos|amp|lt|gt);?/$EntityToChar{lc($1)} || warn "no entity for: $1"/egi;
Condition50%1/2
$EntityToChar{lc $1} || warn("no entity for: $1")
l!l
10
MC/DC0%0/1
$EntityToChar{lc $1} || warn("no entity for: $1")
$EntityToChar{lc $1}
Truth table50%1/2
A
A= $EntityToChar{lc $1}
Aresult
11
00
2206 }
2207  
2208 # Remove all CSS comments
2209 331 s{/\*.*?\*/}{}sg;
2210  
2211 # Remove any CSS imports
2212 331 s{(\@import[^;]+;?)}{}sg;
2213  
2214 # Have to upgrade string to unicode string if entity expansion
2215 # resulted in non-ascii char
2216 331 ▶ utf8::upgrade($_) if $UnicodeEntity;
Branch: 1 branch
BranchTrueFalseTotal
if $UnicodeEntity 1 330 331
2217  
2218 331 ▶ warn "cleanup_style Content=$_" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 331 331
2219 }
2220  
2221 }
2222  
2223 =item I<defang_stylerule($SelectorsIn, $StyleRules, $lcTag, $IsAttr, $AttributeHash, $HtmlR, $OutR)>
2224  
2225 Defangs style data.
2226  
2227 =over 4
2228  
2229 =item B<Method parameters>
2230  
2231 =over 4
2232  
2233 =item I<$SelectorsIn>
2234  
2235 An array reference to the selectors in the style tag/attribute contents.
2236  
2237 =item I<$StyleRules>
2238  
2239 An array reference to the declaration blocks in the style tag/attribute contents.
2240  
2241 =item I<$lcTag>
2242  
2243 Lower case version of the HTML tag that is currently being parsed.
2244  
2245 =item I<$IsAttr>
2246  
2247 Whether we are currently parsing a style attribute or style tag. $IsAttr will be true if we are currently parsing a style attribute.
2248  
2249 =item I<$HtmlR>
2250  
2251 A scalar reference to the input HTML.
2252  
2253 =item I<$OutR>
2254  
2255 A scalar reference to the processed output so far.
2256  
2257 =back
2258  
2259 =back
2260  
2261 =cut
2262 331 ▶sub defang_stylerule {
Subroutine defang_stylerule: called CC=45 SCAR=38.5
Pod documented
2263 331 my ($Self, $SelectorsIn, $StyleRules, $lcTag, $IsAttr, $AttributeHash, $HtmlR, $OutR) = @_;
2264  
2265 # Formatting of each declaration (whitespace, separators), per rule. Kept
2266 # by position rather than by selector text, so it survives a css_callback
2267 # renaming a selector, and repeated selectors don't overwrite each other
2268 331 my @SelectorStyleKeyExtraData;
2269  
2270 331 my (@Selectors, @SelectorRules);
2271  
2272 331 foreach my $Selector (@$SelectorsIn) {
2273  
2274 420 ▶ warn "defang_stylerule Selector=$Selector" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 420 420
2275 420 my $Rule = shift @$StyleRules;
2276 420 my (@SelectorRule, @KeyValueRules, %StyleKeyExtraData);
2277  
2278 # Split style declaration to basic elements
2279 420 ▶ while($Rule =~ s{^(\{?\s*)([^:]+?)(\s*:\s*)((?:)?)([^;\}]+)()?(\s*;?)(\s*\}?)}{}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Rule =~ s/^(\{?\s*)([^:]+?)(\s*:\s*)((?:)?)([^;\}]+)()?(\s*;?)(\s*\}?)//) 582 420 1002
2280 582 my ($KeyPilot, $Key, $Separator, $QuoteStart, $Value, $QuoteEnd, $ValueEnd, $ValueTrail) = ($1, $2, $3, $4, $5, $6, $7, $8);
2281
2282 582 ▶ warn "defang_stylerule Key=$Key Value=$Value Separator=$Separator ValueEnd=$ValueEnd" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 582 582
2283 # Store everything except style property and value in a hash
2284 582 $StyleKeyExtraData{lc $Key} = [$KeyPilot, $Separator, $QuoteStart, $QuoteEnd, $ValueEnd, $ValueTrail];
2285 582 my $DefangStyleRule = $Self->{defang_default};
2286  
2287 # If the style value has a URL in it and URL callback has been supplied, make a url_callback
2288 # Check every url() in the value (there can be several, e.g. layered
2289 # backgrounds), and defang the declaration if any of them is defanged
2290 582 ▶ if ($Self->{url_callback}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Self->{"url_callback"}) 27 555 582
2291 27 our $StartPos = 0;
2292 27 my $AnyUrlDefanged = 0;
2293 27 ▶ while ($Value =~ m/\burl\(\s*((?:['"])?)(?{ $StartPos = pos; })(.*?)\1\s*\)/gci) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Value =~ /\burl\(\s*((?:['"])?)(?{ $HTML::Defang::StartPos = pos $_; })(.*?)\1\s*\)/cig) 22 27 49
2294 22 ▶ my ($UrlOrig, $Url) = $2 ? ($2, $2) : ('', '');
Branch: 1 branch
BranchTrueFalseTotal
$2 ? : 22 0 22
2295 22 my $EndPos = pos($Value);
2296 22 ▶ warn "defang_stylerule Url found in style property value. Url=$Url" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 22 22
2297 22 ▶ my $lcAttrKey = $IsAttr ? "style" : undef;
Branch: 1 branch
BranchTrueFalseTotal
$IsAttr ? : 8 14 22
2298 22 ▶ if ($Url) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Url) 22 0 22
2299 22 $DefangStyleRule = $Self->{url_callback}->($Self->{context}, $Self, $lcTag, $lcAttrKey, \$Url, $AttributeHash, $HtmlR, $OutR, lc $Key);
2300 22 ▶ $AnyUrlDefanged = 1 if defined $DefangStyleRule && $DefangStyleRule == DEFANG_ALWAYS;
Branch: 1 branch
BranchTrueFalseTotal
if defined $DefangStyleRule and $DefangStyleRule == 1 7 15 22
Condition66%2/3
defined $DefangStyleRule and $DefangStyleRule == 1
!ll&&!rl&&r
0157
MC/DC50%1/2
defined $DefangStyleRule and $DefangStyleRule == 1
defined $DefangStyleRule $DefangStyleRule == 1
Truth table66%2/3
A and B
A= defined $DefangStyleRuleB= $DefangStyleRule == 1
ABresult
0X0
100
111
2301 }
2302 # Save back any changes
2303 22 ▶ warn "defang_stylerule After URL callback, Value=$Value DefangStyleRule=$DefangStyleRule" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 22 22
2304 22 ▶ if ($UrlOrig) {
Branch: 1 branch
BranchTrueFalseTotal
if ($UrlOrig) 22 0 22
2305 22 substr($Value, $StartPos, length($UrlOrig), $Url);
2306 22 pos($Value) = $EndPos - length($UrlOrig) + length($Url);
2307 }
2308 }
2309 27 ▶ $DefangStyleRule = DEFANG_ALWAYS if $AnyUrlDefanged;
Branch: 1 branch
BranchTrueFalseTotal
if $AnyUrlDefanged 7 20 27
2310 }
2311  
2312 # Save the style property, value and defang flag
2313 582 push @KeyValueRules, [$Key, $Value, $DefangStyleRule];
2314 582 ▶ warn "defang_stylerule Key=$Key Value=$Value DefangStyleRule=$DefangStyleRule" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 582 582
2315  
2316 }
2317  
2318 420 push (@SelectorRule, \@KeyValueRules);
2319 420 push (@Selectors, $Selector);
2320 420 push (@SelectorRules, \@SelectorRule);
2321 420 push @SelectorStyleKeyExtraData, \%StyleKeyExtraData;
2322  
2323 }
2324  
2325 # If a CSS callback is supplied, we call that
2326 331 ▶ $Self->{css_callback}->($Self->{context}, $Self, \@Selectors, \@SelectorRules, $lcTag, $IsAttr, $OutR) if $Self->{css_callback};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"css_callback"} 165 166 331
2327  
2328 warn "defang_stylerule More selectors($#Selectors) than selector rules($#SelectorRules)" if $Self->{Debug}
2329 331 ▶ && $#Selectors > $#SelectorRules;
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} and $#Selectors > $#SelectorRules 0 331 331
Condition33%1/3
$Self->{"Debug"} and $#Selectors > $#SelectorRules
!ll&&!rl&&r
33100
MC/DC0%0/2
$Self->{"Debug"} and $#Selectors > $#SelectorRules
$Self->{"Debug"} $#Selectors > $#SelectorRules
Truth table33%1/3
A and B
A= $Self->{"Debug"}B= $#Selectors > $#SelectorRules
ABresult
0X0
100
111
2330  
2331 331 my $Counter = 0;
2332 331 foreach my $Selector (@Selectors) {
2333  
2334 420 my $SelectorRule = $SelectorRules[$Counter];
2335 420 ▶ my $ExtraData = ($SelectorStyleKeyExtraData[$Counter] ||= {});
Condition50%1/2
$SelectorStyleKeyExtraData[$Counter] ||= {}
l!l
4200
MC/DC0%0/1
$SelectorStyleKeyExtraData[$Counter] ||= {}
$SelectorStyleKeyExtraData[$Counter]
Truth table50%1/2
A
A= $SelectorStyleKeyExtraData[$Counter]
Aresult
11
00
2336 420 my $Rule;
2337  
2338 420 ▶ for (my $j = 0; $j < @$SelectorRule; $j++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < @$SelectorRule) 420 420 840
2339 420 my $KeyValueRules = $SelectorRule->[$j];
2340
2341 420 ▶ for (my $k = 0; $k < @$KeyValueRules; $k++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($k < @$KeyValueRules) 639 420 1059
2342 639 my ($Key, $Value, $Defang) = @{$KeyValueRules->[$k]};
2343  
2344 639 ▶ my $v = ($ExtraData->{lc $Key} ||= []);
Condition100%2/2
$$ExtraData{lc $Key} ||= []
l!l
528111
MC/DC100%1/1
$$ExtraData{lc $Key} ||= []
$$ExtraData{lc $Key}
Truth table100%2/2
A
A= $$ExtraData{lc $Key}
Aresult
11
00
2345 639 my ($KeyPilot, $Separator, $QuoteStart, $QuoteEnd, $ValueEnd, $ValueTrail) = @$v;
2346  
2347 # Always need a separator
2348 639 ▶ $v->[1] = defined $v->[1] ? $v->[1] : ':';
Branch: 1 branch
BranchTrueFalseTotal
defined $v->[1] ? : 528 111 639
2349 # If an intermediate style property-value pair doesn't have a terminating semi-colon, add it
2350 639 ▶ if ($k < @$KeyValueRules - 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($k < @$KeyValueRules - 1) 262 377 639
2351 262 ▶ $v->[4] .= ";" if !defined $v->[4] || $v->[4] !~ m/;/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v->[4] and $v->[4] =~ /;/ 91 171 262
Condition100%3/3
defined $v->[4] and $v->[4] =~ /;/
!ll&&!rl&&r
5437171
MC/DC100%2/2
defined $v->[4] and $v->[4] =~ /;/
defined $v->[4] $v->[4] =~ /;/
Truth table100%3/3
A and B
A= defined $v->[4]B= $v->[4] =~ /;/
ABresult
0X0
100
111
2352 }
2353  
2354 }
2355
2356 }
2357  
2358 420 $Counter++;
2359 }
2360
2361 331 $Counter = 0;
2362 331 foreach my $Selector (@Selectors) {
2363
2364 420 ▶ $SelectorsIn->[$Counter] = $Selector if $SelectorsIn->[$Counter] && !$IsAttr;
Branch: 1 branch
BranchTrueFalseTotal
if $SelectorsIn->[$Counter] and not $IsAttr 128 292 420
Condition100%3/3
$SelectorsIn->[$Counter] and not $IsAttr
!ll&&!rl&&r
142150128
MC/DC100%2/2
$SelectorsIn->[$Counter] and not $IsAttr
$SelectorsIn->[$Counter] not $IsAttr
Truth table100%3/3
A and not(B)
A= $SelectorsIn->[$Counter]B= not $IsAttr
ABresult
0X0
100
111
2365 420 my $SelectorRule = $SelectorRules[$Counter];
2366 420 my $ExtraData = $SelectorStyleKeyExtraData[$Counter];
2367 420 my $Rule;
2368
2369 420 foreach my $KeyRules (@$SelectorRule) {
2370
2371 420 foreach my $KeyValueRule (@$KeyRules) {
2372
2373 639 my ($Key, $Value, $Defang) = @$KeyValueRule;
2374 639 my $v = $ExtraData->{lc $Key};
2375 639 ▶ my ($KeyPilot, $Separator, $QuoteStart, $QuoteEnd, $ValueEnd, $ValueTrail) = @{$v || []};
Condition50%1/2
$v || []
l!l
6390
MC/DC0%0/1
$v || []
$v
Truth table50%1/2
A
A= $v
Aresult
11
00
2376  
2377 # Flag to defang if a url, expression or unallowed character found
2378 639 ▶ if ($Defang == DEFANG_DEFAULT) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Defang == 2) 354 285 639
2379 354 ▶ $Defang = $Value =~ m{^\s*[a-z0-9%!"'`:()#\s.,\/+-]+\s*;?\s*$}i ? DEFANG_NONE : DEFANG_ALWAYS;
Branch: 1 branch
BranchTrueFalseTotal
$Value =~ m[^\s*[a-z0-9%!"'`:()#\s.,\/+-]+\s*;?\s*$]i ? : 351 3 354
2380 354 ▶ $Defang = $Value =~ m{\burl\s*\(}i ? DEFANG_ALWAYS : $Defang;
Branch: 1 branch
BranchTrueFalseTotal
$Value =~ /\burl\s*\(/i ? : 25 329 354
2381 354 ▶ $Defang = $Value =~ m{\bexpression\s*\(}i ? DEFANG_ALWAYS : $Defang;
Branch: 1 branch
BranchTrueFalseTotal
$Value =~ /\bexpression\s*\(/i ? : 3 351 354
2382 }
2383  
2384 ($KeyPilot, $Key, $Separator, $QuoteStart, $Value, $QuoteEnd, $ValueEnd, $ValueTrail) =
2385 639 ▶ map { defined($_) ? $_ : "" }
Branch: 1 branch
BranchTrueFalseTotal
defined $_ ? : 4611 501 5112
2386 ($KeyPilot, $Key, $Separator, $QuoteStart, $Value, $QuoteEnd, $ValueEnd, $ValueTrail);
2387
2388 # Comment out the style property-value pair if $Defang
2389 639 my $CommentDefang = 0;
2390 639 ▶ if ($Defang != DEFANG_NONE) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Defang != 0) 115 524 639
2391 115 ▶ if ($Self->{delete_defang_content}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Self->{'delete_defang_content'}) { } 4 111 115
2392 4 $KeyPilot = $Key = $Separator = $QuoteStart = $Value = $QuoteEnd = $ValueEnd = $ValueTrail = '';
2393 } else {
2394 111 $CommentDefang = 1;
2395 }
2396 }
2397  
2398 # Put the rule together back
2399 639 ▶ if (defined($Key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $Key) 639 0 639
2400 639 my $RuleContent = join "", $Key, $Separator, $QuoteStart, $Value, $QuoteEnd, $ValueEnd;
2401 639 ▶ if ($CommentDefang) {
Branch: 1 branch
BranchTrueFalseTotal
if ($CommentDefang) 111 528 639
2402 # Strip any mismatched comment markers, then add our own
2403 111 $RuleContent =~ s{/\*}{}g;
2404 111 $RuleContent =~ s{\*/}{}g;
2405 111 $RuleContent = "/*" . $RuleContent . "*/";
2406 }
2407 639 $Rule .= join "", $KeyPilot, $RuleContent, $ValueTrail;
2408 }
2409
2410 639 ▶ warn "defang_stylerule Rule=$Rule" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 639 639
2411  
2412 }
2413  
2414 }
2415  
2416 # Modify the original array
2417 420 $StyleRules->[$Counter] = $Rule;
2418 420 $Counter++;
2419 }
2420  
2421 }
2422  
2423 =item I<defang_attributes($OutR, $HtmlR, $TagOps, $OpenAngle, $IsEndTag, $Tag, $TagTrail, $Attributes, $CloseAngle)>
2424  
2425 Defangs attributes, defangs tags, does tag, attrib, css and url callbacks.
2426  
2427 =over 4
2428  
2429 =item B<Method parameters>
2430  
2431 For a description of the method parameters, see documentation of defang_script_tag() method
2432  
2433 =back
2434  
2435 =cut
2436 1123 ▶sub defang_attributes {
Subroutine defang_attributes: called CC=43 SCAR=40.9
Pod documented
2437 1123 my ($Self, $OutR, $HtmlR, $TagOps, $OpenAngle, $IsEndTag, $lcTag, $TagTrail, $Attributes, $CloseAngle) = @_;
2438  
2439 1123 my $Debug = $Self->{Debug};
2440  
2441 1123 my $DefangTag = $Self->{defang_default};
2442 1123 my ($DefangTagUrlOverride, $DefangTagAttrOverride);
2443  
2444 # Create a key -> \value mapping of all attributes up front
2445 # so we have a complete hash for each callback
2446 1123 my %AttributeHash;
2447 1123 for my $Attr (@$Attributes) {
2448 744 my ($AttrKey, $AttrValR) = ($Attr->[0], \$Attr->[4]);
2449  
2450 744 ▶ my $lcAttrKey = $Attr->[7] = defined $AttrKey ? lc($AttrKey) : "";
Branch: 1 branch
BranchTrueFalseTotal
defined $AttrKey ? : 743 1 744
2451  
2452 # Get the attribute value cleaned up
2453 744 $$AttrValR = $Self->cleanup_attribute($$AttrValR);
2454 744 ▶ warn "defang_attributes cleaned AttrVal=$$AttrValR" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 744 744
2455  
2456 744 $AttributeHash{$lcAttrKey} = $AttrValR;
2457 }
2458  
2459 # Callback if the tag is in @$tags_to_callback
2460 1123 ▶ if (exists($Self->{tags_to_callback}->{$lcTag})) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $Self->{"tags_to_callback"}{$lcTag}) 115 1008 1123
2461 115 ▶ warn "defang_attributes Calling tags_callback for $lcTag" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 115 115
2462 115 $DefangTag = $Self->{tags_callback}->($Self->{context}, $Self, $OpenAngle, $lcTag, $IsEndTag, \%AttributeHash, $CloseAngle, $HtmlR, $OutR);
2463 }
2464  
2465 # Now process each attribute
2466 1123 foreach my $Attr (@$Attributes) {
2467 744 my ($lcAttrKey, $AttrKey, $AttrValR) = ($Attr->[7], $Attr->[0], \$Attr->[4]);
2468  
2469 744 ▶ warn "defang_attributes Tag=$lcTag lcAttrKey=$lcAttrKey AttrVal=$$AttrValR" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 744 744
2470  
2471 $Self->scope_attribute($lcTag, $lcAttrKey, $AttrValR)
2472 744 ▶ if defined $Self->{scope_id} && defined $$AttrValR;
Branch: 1 branch
BranchTrueFalseTotal
if defined $Self->{"scope_id"} and defined $$AttrValR 16 728 744
Condition66%2/3
defined $Self->{"scope_id"} and defined $$AttrValR
!ll&&!rl&&r
728016
MC/DC50%1/2
defined $Self->{"scope_id"} and defined $$AttrValR
defined $Self->{"scope_id"} defined $$AttrValR
Truth table66%2/3
A and B
A= defined $Self->{"scope_id"}B= defined $$AttrValR
ABresult
0X0
100
111
2473  
2474 744 my $AttribRule = "";
2475 744 ▶ if (ref($Tags{$lcTag}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $Tags{$lcTag} eq "HASH") 658 86 744
2476 658 $AttribRule = $Tags{$lcTag}{$lcAttrKey};
2477 }
2478  
2479 744 my $DefangAttrib = $Self->{defang_default};
2480  
2481 744 ▶ $AttribRule ||= $CommonAttributes{$lcAttrKey};
Condition100%3/3
$AttribRule ||= $CommonAttributes{$lcAttrKey}
l!l&&r!l&&!r
245265234
MC/DC100%2/2
$AttribRule ||= $CommonAttributes{$lcAttrKey}
$AttribRule $CommonAttributes{$lcAttrKey}
Truth table100%3/3
A ||= B
A= $AttribRuleB= $CommonAttributes{$lcAttrKey}
ABresult
1X1
011
000
2482 744 ▶ warn "defang_attributes AttribRule=$AttribRule" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 744 744
2483
2484 # If this is a URL type $AttrKey and URL callback method is supplied, make a url_callback
2485 744 ▶ if ($Self->{url_callback} && $AttribRule && exists($UrlRules{$AttribRule})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Self->{"url_callback"} and $AttribRule and exists $UrlRules{$AttribRule}) 23 721 744
Condition83%5/6
$Self->{"url_callback"} and $AttribRule and exists $UrlRules{$AttribRule}
!ll&&!rl&&r
7002123
$Self->{"url_callback"} and $AttribRule
!ll&&!rl&&r
700044
MC/DC66%2/3
$Self->{"url_callback"} and $AttribRule and exists $UrlRules{$AttribRule}
$Self->{"url_callback"} $AttribRule exists $UrlRules{$AttribRule}
Truth table75%3/4
A and B and C
A= $Self->{"url_callback"}B= $AttribRuleC= exists $UrlRules{$AttribRule}
ABCresult
0XX0
10X0
1100
1111
2486 23 ▶ warn "defang_attributes Making URL callback" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 23 23
2487 23 ($DefangAttrib, $DefangTagUrlOverride) = $Self->{url_callback}->($Self->{context}, $Self, $lcTag, $lcAttrKey, $AttrValR, \%AttributeHash, $HtmlR, $OutR, { defang_attrib => $DefangAttrib, attrib_rule => $AttribRule });
2488 23 ▶ die "url_callback reset" if !defined pos($$HtmlR);
Branch: 1 branch
BranchTrueFalseTotal
unless defined pos $$HtmlR 0 23 23
2489 }
2490  
2491 # We have a style attribute, so we call defang_style
2492 744 ▶ if ($lcAttrKey eq "style") {
Branch: 1 branch
BranchTrueFalseTotal
if ($lcAttrKey eq "style") 209 535 744
2493 209 ▶ warn "defang_attributes Found style attribute, calling defang_style" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 209 209
2494 209 $$AttrValR = $Self->defang_style_text($$AttrValR, $lcTag, 1, \%AttributeHash, $HtmlR, $OutR);
2495 }
2496  
2497 # If a attribute callback is supplied and its interested in this attribute, we make a attribs_callback
2498 744 ▶ if ($Self->{attribs_callback} && exists($Self->{attribs_to_callback}->{$lcAttrKey})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Self->{"attribs_callback"} and exists $Self->{"attribs_to_callback"}{$lcAttrKey}) 0 744 744
Condition33%1/3
$Self->{"attribs_callback"} and exists $Self->{"attribs_to_callback"}{$lcAttrKey}
!ll&&!rl&&r
74400
MC/DC0%0/2
$Self->{"attribs_callback"} and exists $Self->{"attribs_to_callback"}{$lcAttrKey}
$Self->{"attribs_callback"} exists $Self->{"attribs_to_callback"}{$lcAttrKey}
Truth table33%1/3
A and B
A= $Self->{"attribs_callback"}B= exists $Self->{"attribs_to_callback"}{$lcAttrKey}
ABresult
0X0
100
111
2499 0 ▶ warn "defang_attributes Making attribute callback for Tag=$lcTag AttrKey=$AttrKey" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 0 0
2500 0 (my $DefangResult, $DefangTagAttrOverride) = $Self->{attribs_callback}->($Self->{context}, $Self, $lcTag, $lcAttrKey, $AttrValR, $HtmlR, $OutR);
2501 # Only use new result if not already DEFANG_ALWAYS from url_callback
2502 0 ▶ $DefangAttrib = $DefangResult if $DefangAttrib != DEFANG_ALWAYS;
Branch: 1 branch
BranchTrueFalseTotal
if $DefangAttrib != 1 0 0 0
2503 }
2504  
2505 # Check if the final attribute value needs defanging
2506 744 $DefangAttrib = $Self->defang_attribute_value($AttrValR, $AttribRule, $DefangAttrib);
2507  
2508 # Store the attribute defang flag
2509 744 $Attr->[8] = $DefangAttrib;
2510  
2511 }
2512  
2513 1123 my @OutputAttributes;
2514  
2515 1123 foreach my $Attr (@$Attributes) {
2516
2517 744 my $lcAttr = $Attr->[7];
2518  
2519 # If the attribute is deleted don't output it
2520 744 ▶ unless ($AttributeHash{$lcAttr}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($AttributeHash{$lcAttr}) 25 719 744
2521 25 ▶ warn "defang_attributes Marking attribute $lcAttr for deletion" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 25 25
2522 25 next;
2523 }
2524  
2525 # And we attach the defang string here, if the attribute should be defanged
2526 # (attribute could be undef for buggy html, eg <ahref=blah>)
2527 719 ▶ if ($Attr->[8] != DEFANG_NONE) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Attr->[8] != 0) 357 362 719
2528 357 ▶ if ($Self->{delete_defang_content}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Self->{'delete_defang_content'}) { } 7 350 357
2529 7 @$Attr = ('') x 7;
2530 } else {
2531 $Attr->[0] = $Self->{defang_string} . ($Attr->[0] || '')
2532 350 ▶ if $Self->{allow_double_defang} || ($Attr->[0] || '') !~ $Self->{defang_re};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"allow_double_defang"} or not +($Attr->[0] || "") =~ /$Self->{"defang_re"}/ 350 0 350
Condition71%5/7
$Self->{"allow_double_defang"} or not +($Attr->[0] || "") =~ /$Self->{"defang_re"}/
l!l&&r!l&&!r
03500
$Attr->[0] || ''
l!l
3491
$Attr->[0] || ''
l!l
3491
MC/DC50%1/2
$Self->{"allow_double_defang"} or not +($Attr->[0] || "") =~ /$Self->{"defang_re"}/
$Self->{"allow_double_defang"} $Attr->[0]
Truth table66%2/3
A or not(B)
A= $Self->{"allow_double_defang"}B= $Attr->[0]
ABresult
1X1
001
010
2533 }
2534 }
2535  
2536 # Remove non-attribute values so they're not in the output
2537 719 splice(@$Attr, 7);
2538  
2539 # Requote specials in attribute value
2540 719 ▶ if (defined $Attr->[4]) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $Attr->[4]) 719 0 719
2541 719 ▶ my $QuoteRe = $QuoteRe{$Attr->[3]} || $QuoteRe{""};
Condition33%1/3
$QuoteRe{$Attr->[3]} || $QuoteRe{''}
l!l&&r!l&&!r
71900
MC/DC0%0/2
$QuoteRe{$Attr->[3]} || $QuoteRe{''}
$QuoteRe{$Attr->[3]} $QuoteRe{''}
Truth table33%1/3
A || B
A= $QuoteRe{$Attr->[3]}B= $QuoteRe{''}
ABresult
1X1
011
000
2542 719 $Attr->[4] =~ s/$CtrlChars//go; # strip ctrls
2543 719 $Attr->[4] =~ s/$QuoteRe/'&'.$CharToEntity{$1}.';'/eg;
2544 }
2545  
2546 # Add to attributes to output
2547 719 push @OutputAttributes, $Attr;
2548  
2549 # Remove all processed attributes in the hash, so we can track ones that we added
2550 719 delete $AttributeHash{$lcAttr};
2551 }
2552  
2553 # Append all remaining attribute keys (which must have been newly added attributes by
2554 # the callback)and values in no particular order
2555 1123 my $QuoteRe = $QuoteRe{'"'};
2556 1123 ▶ while (my ($Key,$Value) = each %AttributeHash ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %AttributeHash) 29 1123 1152
2557 29 my $Attr = [" " . $Key, "", "=", '"', $$Value, '"', ""];
2558 29 ▶ if (defined $Attr->[4]) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $Attr->[4]) { } 28 1 29
2559 28 $Attr->[4] =~ s/$CtrlChars//g; # strip ctrls
2560 0 $Attr->[4] =~ s/$QuoteRe/'&'.$CharToEntity{$1}.';'/eg
2561 } else {
2562 1 @$Attr[2..6] = (undef) x 5;
2563 }
2564 29 push @OutputAttributes, $Attr;
2565 }
2566  
2567 # Replace attributes array with just the ones we want to output
2568 1123 @$Attributes = @OutputAttributes;
2569  
2570 # If its a known tag, we whitelist it
2571 1123 ▶ if ($DefangTag == DEFANG_DEFAULT && (my $TagOps = $Tags{$lcTag})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($DefangTag == 2 and my $TagOps = $Tags{$lcTag}) 966 157 1123
Condition100%3/3
$DefangTag == 2 and my $TagOps = $Tags{$lcTag}
!ll&&!rl&&r
7582966
MC/DC100%2/2
$DefangTag == 2 and my $TagOps = $Tags{$lcTag}
$DefangTag == 2 my $TagOps = $Tags{$lcTag}
Truth table100%3/3
A and B
A= $DefangTag == 2B= my $TagOps = $Tags{$lcTag}
ABresult
0X0
100
111
2572 966 $DefangTag = DEFANG_NONE;
2573 }
2574 # Unless we have overrides
2575 1123 ▶ $DefangTag = DEFANG_ALWAYS
Branch: 1 branch
BranchTrueFalseTotal
if defined $DefangTagUrlOverride and $DefangTagUrlOverride == 1 0 1123 1123
Condition33%1/3
defined $DefangTagUrlOverride and $DefangTagUrlOverride == 1
!ll&&!rl&&r
112300
MC/DC0%0/2
defined $DefangTagUrlOverride and $DefangTagUrlOverride == 1
defined $DefangTagUrlOverride $DefangTagUrlOverride == 1
Truth table33%1/3
A and B
A= defined $DefangTagUrlOverrideB= $DefangTagUrlOverride == 1
ABresult
0X0
100
111
2576 if defined($DefangTagUrlOverride) && $DefangTagUrlOverride == DEFANG_ALWAYS;
2577 1123 ▶ $DefangTag = DEFANG_ALWAYS
Branch: 1 branch
BranchTrueFalseTotal
if defined $DefangTagAttrOverride and $DefangTagAttrOverride == 1 0 1123 1123
Condition33%1/3
defined $DefangTagAttrOverride and $DefangTagAttrOverride == 1
!ll&&!rl&&r
112300
MC/DC0%0/2
defined $DefangTagAttrOverride and $DefangTagAttrOverride == 1
defined $DefangTagAttrOverride $DefangTagAttrOverride == 1
Truth table33%1/3
A and B
A= defined $DefangTagAttrOverrideB= $DefangTagAttrOverride == 1
ABresult
0X0
100
111
2578 if defined($DefangTagAttrOverride) && $DefangTagAttrOverride == DEFANG_ALWAYS;
2579  
2580 1123 return $DefangTag;
2581 }
2582  
2583 744 ▶sub defang_attribute_value {
Subroutine defang_attribute_value: called CC=12 SCAR=25.0
Pod undocumented
2584 744 my ($Self, $AttrValR, $AttribRule, $DefangAttrib) = @_;
2585  
2586 744 my $Debug = $Self->{Debug};
2587  
2588 744 my $AttrValStripped = $Self->strip_attribute($$AttrValR);
2589  
2590 744 ▶ warn "defang_attribute_value AttrVal=$$AttrValR AttrValStripped=$AttrValStripped" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 744 744
2591  
2592 744 ▶ if (($DefangAttrib == DEFANG_DEFAULT) && $AttribRule) {
Branch: 2 branches
BranchTrueFalseTotal
if ($DefangAttrib == 2 and $AttribRule) { } 487 257 744
elsif (not $AttribRule and $DefangAttrib != 0) { } 234 46 280
Condition100%3/3
$DefangAttrib == 2 and $AttribRule
!ll&&!rl&&r
23234487
MC/DC100%2/2
$DefangAttrib == 2 and $AttribRule
$DefangAttrib == 2 $AttribRule
Truth table100%3/3
A and B
A= $DefangAttrib == 2B= $AttribRule
ABresult
0X0
100
111
2593 487 my $Rule = $Rules{$AttribRule};
2594 487 ▶ warn "defang_attributes AttribRule=$AttribRule Rule=$Rule" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 487 487
2595  
2596 # We whitelist the attribute if the value matches the rule
2597 487 ▶ if (ref($Rule) eq "Regexp") {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $Rule eq "Regexp") 403 84 487
2598 403 ▶ $DefangAttrib = ($AttrValStripped =~ $Rule) ? DEFANG_NONE : DEFANG_ALWAYS;
Branch: 1 branch
BranchTrueFalseTotal
$AttrValStripped =~ /$Rule/ ? : 348 55 403
2599 }
2600  
2601 # Hack. Ref to array is a blacklist regexp
2602 487 ▶ if (ref($Rule) eq "ARRAY") {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $Rule eq "ARRAY") 84 403 487
2603 84 ▶ $DefangAttrib = ($AttrValStripped =~ $Rule->[0]) ? DEFANG_ALWAYS : DEFANG_NONE;
Branch: 1 branch
BranchTrueFalseTotal
$AttrValStripped =~ /$Rule->[0]/i ? : 73 11 84
2604 }
2605
2606 ▶ } elsif (!$AttribRule && $DefangAttrib != DEFANG_NONE) {
Condition66%2/3
not $AttribRule and $DefangAttrib != 0
!ll&&!rl&&r
230234
MC/DC50%1/2
not $AttribRule and $DefangAttrib != 0
not $AttribRule $DefangAttrib != 0
Truth table66%2/3
not(A) and B
A= not $AttribRuleB= $DefangAttrib != 0
ABresult
0X0
100
111
2607 234 $DefangAttrib = DEFANG_ALWAYS;
2608 }
2609  
2610 744 ▶ warn "defang_attribute_value DefangAttrib=$DefangAttrib" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 744 744
2611  
2612 744 return $DefangAttrib;
2613 }
2614  
2615 97 ▶sub track_implicit_tags {
Subroutine track_implicit_tags: called CC=9 SCAR=22.0
Pod undocumented
2616 97 my ($Self, $OutR, $HtmlR, $lcTag, $IsEndTag) = @_;
2617  
2618 97 my $OpenedTags = $Self->{opened_tags};
2619 97 ▶ return if !@$OpenedTags;
Branch: 1 branch
BranchTrueFalseTotal
unless @$OpenedTags 39 58 97
2620  
2621 # If just closing the last tag, nothing to do
2622 58 my $LastTag = $OpenedTags->[-1]->[0];
2623  
2624 # Are we expecting a particular tag based on last open tag?
2625 58 ▶ if (my $ImplicitTags = $ImplicitOpenTags{$LastTag}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ImplicitTags = $ImplicitOpenTags{$LastTag}) 22 36 58
2626  
2627 # We didn't get a tag we were expecting (eg <table><div> rather
2628 # than <table><tbody><tr><td><div>), so insert opening tags recursively
2629 22 $LastTag = $lcTag;
2630 22 ▶ while ($ImplicitTags && (!$ImplicitTags->{$LastTag} || $IsEndTag)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ImplicitTags and !$ImplicitTags->{$LastTag} || $IsEndTag) 6 21 27
Condition83%5/6
$ImplicitTags and !$ImplicitTags->{$LastTag} || $IsEndTag
!ll&&!rl&&r
2196
not $ImplicitTags->{$LastTag} or $IsEndTag
l!l&&r!l&&!r
6019
MC/DC66%2/3
$ImplicitTags and !$ImplicitTags->{$LastTag} || $IsEndTag
$ImplicitTags not $ImplicitTags->{$LastTag} $IsEndTag
Truth table75%3/4
A and not(B) or C
A= $ImplicitTagsB= not $ImplicitTags->{$LastTag}C= $IsEndTag
ABCresult
0XX0
1000
11X1
1011
2631 6 my $Tag = $ImplicitTags->{default};
2632 # Don't insert implicit tag if it's actually the one we actually just parsed
2633 6 ▶ last if !$IsEndTag && $Tag eq $lcTag;
Branch: 1 branch
BranchTrueFalseTotal
if not $IsEndTag and $Tag eq $lcTag 1 5 6
Condition100%3/3
not $IsEndTag and $Tag eq $lcTag
!ll&&!rl&&r
231
MC/DC100%2/2
not $IsEndTag and $Tag eq $lcTag
not $IsEndTag $Tag eq $lcTag
Truth table100%3/3
not(A) and B
A= not $IsEndTagB= $Tag eq $lcTag
ABresult
0X0
100
111
2634 5 $Self->open_tag(1, $OutR, $HtmlR, $Tag, \"");
2635 5 ▶ $$OutR .= "<!-- $Tag implicit open due to $LastTag -->" unless $Self->{quiet};
Branch: 1 branch
BranchTrueFalseTotal
unless $Self->{"quiet"} 5 0 5
2636 5 $LastTag = $Tag;
2637 5 $ImplicitTags = $ImplicitOpenTags{$LastTag};
2638 }
2639 }
2640 }
2641  
2642 152 ▶sub track_in_to_block_tags {
Subroutine track_in_to_block_tags: called CC=6 SCAR=17.9
Pod undocumented
2643 152 my ($Self, $OutR, $HtmlR, $lcTag) = @_;
2644  
2645 # If we've got a block tag, then close any inline tags
2646 # before the block tag. We'll re-opened them again below
2647 152 ▶ if ($BlockTags{$lcTag} && !$TableTags{$lcTag}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($BlockTags{$lcTag} and not $TableTags{$lcTag}) 40 112 152
Condition100%3/3
$BlockTags{$lcTag} and not $TableTags{$lcTag}
!ll&&!rl&&r
407240
MC/DC100%2/2
$BlockTags{$lcTag} and not $TableTags{$lcTag}
$BlockTags{$lcTag} not $TableTags{$lcTag}
Truth table100%3/3
A and not(B)
A= $BlockTags{$lcTag}B= not $TableTags{$lcTag}
ABresult
0X0
100
111
2648 my ($OpenedTags, $ClosedIntoBlockTags, $Quiet)
2649 40 = @$Self{qw(opened_tags closed_into_block_tags quiet)};
2650  
2651 40 ▶ while (@$OpenedTags && $InlineTags{$OpenedTags->[-1]->[0]}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$OpenedTags and $InlineTags{$OpenedTags->[-1][0]}) 3 40 43
Condition100%3/3
@$OpenedTags and $InlineTags{$OpenedTags->[-1][0]}
!ll&&!rl&&r
11293
MC/DC100%2/2
@$OpenedTags and $InlineTags{$OpenedTags->[-1][0]}
@$OpenedTags $InlineTags{$OpenedTags->[-1][0]}
Truth table100%3/3
A and B
A= @$OpenedTagsB= $InlineTags{$OpenedTags->[-1][0]}
ABresult
0X0
100
111
2652 3 push @$ClosedIntoBlockTags, my $POTD = $OpenedTags->[-1];
2653 3 ▶ $$OutR .= "<!-- close inline tag into block -->" unless $Quiet;
Branch: 1 branch
BranchTrueFalseTotal
unless $Quiet 3 0 3
2654 3 $Self->close_tag(1, $OutR, $HtmlR, $POTD->[0], 1);
2655 }
2656 }
2657 }
2658  
2659 147 ▶sub track_out_of_block_tags {
Subroutine track_out_of_block_tags: called CC=10 SCAR=23.7
Pod undocumented
2660 147 my ($Self, $OutR, $HtmlR, $lcTag) = @_;
2661  
2662 147 my $ClosedIntoBlockTags = $Self->{closed_into_block_tags};
2663 147 ▶ return if !@$ClosedIntoBlockTags;
Branch: 1 branch
BranchTrueFalseTotal
unless @$ClosedIntoBlockTags 144 3 147
2664  
2665 # Re-open inline tags into this block
2666  
2667 # Peek ahead. If another block tag, don't do this
2668 return if $$HtmlR =~ m{\G(?=\s*</?($TagNameRE))}gc
2669 3 ▶ && $BlockTags{lc "$1"} && !$TableTags{lc "$1"};
Branch: 1 branch
BranchTrueFalseTotal
if $$HtmlR =~ m[\G(?=\s*</?($TagNameRE))]cg and $BlockTags{lc "$1"} and not $TableTags{lc "$1"} 0 3 3
Condition66%4/6
$$HtmlR =~ m[\G(?=\s*</?($TagNameRE))]cg and $BlockTags{lc "$1"} and not $TableTags{lc "$1"}
!ll&&!rl&&r
210
$$HtmlR =~ m[\G(?=\s*</?($TagNameRE))]cg and $BlockTags{lc "$1"}
!ll&&!rl&&r
201
MC/DC0%0/3
$$HtmlR =~ m[\G(?=\s*</?($TagNameRE))]cg and $BlockTags{lc "$1"} and not $TableTags{lc "$1"}
$$HtmlR =~ m[\G(?=\s*</?($TagNameRE))]cg $BlockTags{lc "$1"} not $TableTags{lc "$1"}
Truth table50%2/4
A and B and not(C)
A= $$HtmlR =~ m[\G(?=\s*</?($TagNameRE))]cgB= $BlockTags{lc "$1"}C= not $TableTags{lc "$1"}
ABCresult
0XX0
10X0
1100
1111
2670  
2671 3 my ($SpanCount, $SpanAttrs) = (0, '');
2672 3 ▶ while (my $POTD = pop @$ClosedIntoBlockTags) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $POTD = pop @$ClosedIntoBlockTags) 3 3 6
2673  
2674 # Don't add more than 3 span tags with same attrs in a row
2675 3 ▶ if ($SpanCount < 3) {
Branch: 1 branch
BranchTrueFalseTotal
if ($SpanCount < 3) 3 0 3
2676 # Add after the current tag is output
2677 3 $Self->track_and_add_tag_to_output($POTD);
2678 3 ▶ $Self->add_to_output("<!-- reopen inline tag after block -->") unless $Self->{quiet};
Branch: 1 branch
BranchTrueFalseTotal
unless $Self->{"quiet"} 3 0 3
2679 }
2680 3 ▶ $SpanCount = $POTD->[0] eq 'span' && $POTD->[1] eq $SpanAttrs ? $SpanCount+1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$POTD->[0] eq 'span' && $POTD->[1] eq $SpanAttrs ? : 2 1 3
Condition66%2/3
$POTD->[0] eq "span" and $POTD->[1] eq $SpanAttrs
!ll&&!rl&&r
102
MC/DC50%1/2
$POTD->[0] eq "span" and $POTD->[1] eq $SpanAttrs
$POTD->[0] eq "span" $POTD->[1] eq $SpanAttrs
Truth table66%2/3
A and B
A= $POTD->[0] eq "span"B= $POTD->[1] eq $SpanAttrs
ABresult
0X0
100
111
2681 3 $SpanAttrs = $POTD->[1];
2682 }
2683 }
2684  
2685 88 ▶sub open_tag {
Subroutine open_tag: called CC=5 SCAR=16.1
Pod undocumented
2686 88 my ($Self, $AddOutput, $OutR, $HtmlR, $lcTag, $TagContentR, $NoBlockCheck) = @_;
2687  
2688 88 $Self->track_implicit_tags($OutR, $HtmlR, $lcTag, 0);
2689 88 ▶ $Self->track_in_to_block_tags($OutR, $HtmlR, $lcTag)
Branch: 1 branch
BranchTrueFalseTotal
unless $NoBlockCheck 85 3 88
2690 unless $NoBlockCheck;
2691  
2692 # Track this tag that was opened (and all attributes, so we can re-open with the same if needed)
2693 88 ▶ if ($Self->{mismatched_tags_to_fix}->{$lcTag}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Self->{"mismatched_tags_to_fix"}{$lcTag}) 61 27 88
2694 61 push @{$Self->{opened_tags}}, [ $lcTag, $$TagContentR ];
2695 61 $Self->{opened_tags_count}->{$lcTag}++;
2696 }
2697 88 ▶ if ($AddOutput) {
Branch: 1 branch
BranchTrueFalseTotal
if ($AddOutput) 8 80 88
2698 8 $$OutR .= "<${lcTag}${$TagContentR}>";
2699 }
2700  
2701 88 ▶ $Self->track_out_of_block_tags($OutR, $HtmlR, $lcTag)
Branch: 1 branch
BranchTrueFalseTotal
unless $NoBlockCheck 85 3 88
2702 unless $NoBlockCheck;
2703  
2704 88 return DEFANG_NONE;
2705 }
2706  
2707 11 my %RECache;
2708 70 ▶sub close_tag {
Subroutine close_tag: called CC=24 SCAR=40.5
Pod undocumented
2709 70 my ($Self, $AddOutput, $OutR, $HtmlR, $lcTag, $NoBlockCheck) = @_;
2710  
2711 my ($OpenedTags, $OpenedTagsCount, $Quiet)
2712 70 = @$Self{qw(opened_tags opened_tags_count quiet)};
2713  
2714 # If just closing the last tag, nothing to do
2715 70 ▶ if (@$OpenedTags && $OpenedTags->[-1]->[0] ne $lcTag) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$OpenedTags and $OpenedTags->[-1][0] ne $lcTag) 9 61 70
Condition100%3/3
@$OpenedTags and $OpenedTags->[-1][0] ne $lcTag
!ll&&!rl&&r
4579
MC/DC100%2/2
@$OpenedTags and $OpenedTags->[-1][0] ne $lcTag
@$OpenedTags $OpenedTags->[-1][0] ne $lcTag
Truth table100%3/3
A and B
A= @$OpenedTagsB= $OpenedTags->[-1][0] ne $lcTag
ABresult
0X0
100
111
2716 9 $Self->track_implicit_tags($OutR, $HtmlR, $lcTag, 1);
2717 }
2718  
2719 70 ▶ $Self->track_in_to_block_tags($OutR, $HtmlR, $lcTag)
Branch: 1 branch
BranchTrueFalseTotal
unless $NoBlockCheck 67 3 70
2720 unless $NoBlockCheck;
2721  
2722 # Check for correctly nested closing tags
2723 70 my $IsTagToFix = $Self->{mismatched_tags_to_fix}->{$lcTag};
2724 70 ▶ if ($IsTagToFix) {
Branch: 1 branch
BranchTrueFalseTotal
if ($IsTagToFix) 66 4 70
2725 66 my ($Found, $ClosingTags) = (0, '');
2726  
2727 # Tag not even open, just defang it
2728 66 ▶ return DEFANG_ALWAYS if !$OpenedTagsCount->{$lcTag};
Branch: 1 branch
BranchTrueFalseTotal
unless $OpenedTagsCount->{$lcTag} 5 61 66
2729  
2730 # Check tag stack up to find mismatches
2731 61 ▶ while (@$OpenedTags) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$OpenedTags) 67 0 67
2732 67 my ($PreviousOpenedTag) = @{$OpenedTags->[-1]};
2733  
2734 67 ▶ if ($PreviousOpenedTag eq $lcTag) {
Branch: 1 branch
BranchTrueFalseTotal
if ($PreviousOpenedTag eq $lcTag) 61 6 67
2735 61 $Found = 1;
2736 61 last;
2737 }
2738  
2739 # Check for tags that don't break out further
2740 6 ▶ if (my $NestList = $MismatchedTagNest{$PreviousOpenedTag}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $NestList = $MismatchedTagNest{$PreviousOpenedTag}) 0 6 6
2741 0 ▶ last if $NestList->{""} || $NestList->{$lcTag};
Branch: 1 branch
BranchTrueFalseTotal
if $NestList->{""} or $NestList->{$lcTag} 0 0 0
Condition0%0/3
$NestList->{""} or $NestList->{$lcTag}
l!l&&r!l&&!r
000
MC/DC0%0/2
$NestList->{""} or $NestList->{$lcTag}
$NestList->{""} $NestList->{$lcTag}
Truth table0%0/3
A or B
A= $NestList->{""}B= $NestList->{$lcTag}
ABresult
1X1
011
000
2742 }
2743  
2744 # Close this mismatched tag
2745 6 ▶ $$OutR .= "<!-- close mismatched tag -->" unless $Quiet;
Branch: 1 branch
BranchTrueFalseTotal
unless $Quiet 6 0 6
2746 6 $Self->close_tag(1, $OutR, $HtmlR, $PreviousOpenedTag);
2747 }
2748  
2749 # Otherwise hit tag that stops breaking out, defang it
2750 61 ▶ if (!$Found) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($Found) 0 61 61
2751 0 return DEFANG_ALWAYS;
2752 }
2753 }
2754  
2755 65 my $Result = DEFANG_NONE;
2756  
2757 65 ▶ if ($IsTagToFix && $Self->{empty_tags_to_collapse}->{$lcTag}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($IsTagToFix and $Self->{"empty_tags_to_collapse"}{$lcTag}) 0 65 65
Condition66%2/3
$IsTagToFix and $Self->{"empty_tags_to_collapse"}{$lcTag}
!ll&&!rl&&r
4610
MC/DC0%0/2
$IsTagToFix and $Self->{"empty_tags_to_collapse"}{$lcTag}
$IsTagToFix $Self->{"empty_tags_to_collapse"}{$lcTag}
Truth table66%2/3
A and B
A= $IsTagToFixB= $Self->{"empty_tags_to_collapse"}{$lcTag}
ABresult
0X0
100
111
2758  
2759 # Check if previous output is open tag, or just comments
2760 0 my $LastTagPos = rindex($$OutR, '<');
2761 0 ▶ while ($LastTagPos >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($LastTagPos >= 0) 0 0 0
2762 0 pos($$OutR) = $LastTagPos;
2763 0 ▶ my $RE = (defined $RECache{$lcTag} ? $RECache{$lcTag} : qr/\G<${lcTag}\b[^<>]*>\s*(?:<|$)/);
Branch: 1 branch
BranchTrueFalseTotal
defined $RECache{$lcTag} ? : 0 0 0
2764 0 ▶ if ($$OutR =~ /$RE/gc) {
Branch: 2 branches
BranchTrueFalseTotal
if ($$OutR =~ /$RE/cg) { } 0 0 0
elsif ($$OutR =~ /\G<!--(?!KEEP)[^<>]*-->\s*(?:<|$)/cg and $LastTagPos > 0) { } 0 0 0
2765 0 substr($$OutR, $LastTagPos) = '';
2766 0 ($AddOutput, $Result) = (0, DEFANG_ALWAYS);
2767 0 last;
2768 ▶ } elsif ($$OutR =~ /\G<!--(?!KEEP)[^<>]*-->\s*(?:<|$)/gc && $LastTagPos > 0) {
Condition0%0/3
$$OutR =~ /\G<!--(?!KEEP)[^<>]*-->\s*(?:<|$)/cg and $LastTagPos > 0
!ll&&!rl&&r
000
MC/DC0%0/2
$$OutR =~ /\G<!--(?!KEEP)[^<>]*-->\s*(?:<|$)/cg and $LastTagPos > 0
$$OutR =~ /\G<!--(?!KEEP)[^<>]*-->\s*(?:<|$)/cg $LastTagPos > 0
Truth table0%0/3
A and B
A= $$OutR =~ /\G<!--(?!KEEP)[^<>]*-->\s*(?:<|$)/cgB= $LastTagPos > 0
ABresult
0X0
100
111
2769 0 $LastTagPos = rindex($$OutR, '<', $LastTagPos-1);
2770 } else {
2771 0 last;
2772 }
2773 }
2774 }
2775  
2776 65 ▶ if ($IsTagToFix) {
Branch: 1 branch
BranchTrueFalseTotal
if ($IsTagToFix) 61 4 65
2777 61 ▶ if ($lcTag eq $Self->{opened_tags}->[-1]->[0]) {
Branch: 1 branch
BranchTrueFalseTotal
if ($lcTag eq $Self->{'opened_tags'}[-1][0]) { } 61 0 61
2778 61 pop @{$Self->{opened_tags}};
2779 61 $Self->{opened_tags_count}->{$lcTag}--;
2780 } else {
2781 0 warn "Unexpected tag stack. Expected $lcTag, found " . $Self->{opened_tags}->[-1]->[0];
2782 }
2783 }
2784 65 ▶ if ($AddOutput) {
Branch: 1 branch
BranchTrueFalseTotal
if ($AddOutput) 40 25 65
2785 40 $$OutR .= "</$lcTag>";
2786 }
2787  
2788 65 ▶ $Self->track_out_of_block_tags($OutR, $HtmlR, $lcTag)
Branch: 1 branch
BranchTrueFalseTotal
unless $NoBlockCheck 62 3 65
2789 unless $NoBlockCheck;
2790  
2791 65 return $Result;
2792 }
2793  
2794 364 ▶sub close_all_tags {
Subroutine close_all_tags: called CC=5 SCAR=18.1
Pod undocumented
2795 364 my ($Self, $OutR, $HtmlR) = @_;
2796  
2797 364 my $RemainingClosingTags = '';
2798  
2799 my ($OpenedTags, $OpenedTagsCount, $Quiet)
2800 364 = @$Self{qw(opened_tags opened_tags_count quiet)};
2801  
2802 364 for (reverse @$OpenedTags) {
2803 31 ▶ $$OutR .= "<!-- close unclosed tag -->" unless $Quiet;
Branch: 1 branch
BranchTrueFalseTotal
unless $Quiet 30 1 31
2804 31 $Self->close_tag(1, $OutR, $HtmlR, $_->[0]);
2805 }
2806  
2807 # Also clear implicit tags
2808 364 $Self->{opened_nested_tags} = [];
2809  
2810 364 ▶ if ($Self->{Debug}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Self->{"Debug"}) 0 364 364
2811 0 warn "Check all tags closed and counts zeroed";
2812 0 ▶ die "Not all tags closed" if grep { $_ > 0 } values %$OpenedTagsCount;
Branch: 1 branch
BranchTrueFalseTotal
if grep {$_ > 0;} values %$OpenedTagsCount 0 0 0
2813 }
2814 }
2815  
2816 =item I<cleanup_attribute($AttributeString)>
2817  
2818 Helper function to cleanup attributes
2819  
2820 =over 4
2821  
2822 =item B<Method parameters>
2823  
2824 =over 4
2825  
2826 =item I<$AttributeString>
2827  
2828 The value of the attribute.
2829  
2830 =back
2831  
2832 =back
2833  
2834 =back
2835  
2836 =back
2837  
2838 =cut
2839 745 ▶sub cleanup_attribute {
Subroutine cleanup_attribute: called CC=16 SCAR=32.6
Pod documented
2840 745 my ($Self, $AttrVal) = @_;
2841  
2842 745 ▶ return (undef, '') unless defined($AttrVal);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $AttrVal 9 736 745
2843  
2844 # Create a "stripped" attribute value which removes all embedded whitespace and control characters
2845  
2846 # Substitute character entities with actual characters
2847 # - in HTML, &#xa; &#x0a; &#x000a; &#10; are all character codes
2848 # - in IE, &#xajavascript is same as &#xa;javascript
2849 # - avoid invalid chars + surrogate pairs
2850 736 my $UnicodeEntity = 0;
2851 736 $AttrVal =~ s{&#(?:x(0?[\da-f]{1,6})|([\d]{1,7}));?}{
2852 138 ▶ my $V = (defined($1) && hex($1)) || (defined($2) && int($2)) || undef;
Condition54%6/11
defined $1 && hex $1 || defined $2 && int $2 || undef
l!l
1380
defined $1 and hex $1 or defined $2 and int $2
l!l&&r!l&&!r
76620
defined $1 and hex $1
!ll&&!rl&&r
62076
defined $2 and int $2
!ll&&!rl&&r
0062
MC/DC0%0/4
defined $1 && hex $1 || defined $2 && int $2 || undef
defined $1 hex $1 defined $2 int $2
Truth table28%2/7
A and B or C and D
A= defined $1B= hex $1C= defined $2D= int $2
ABCDresult
11XX1
0X111
10111
0X0X0
0X100
100X0
10100
2853 138 ▶ $UnicodeEntity = 1 if $V && $V > 127;
Branch: 1 branch
BranchTrueFalseTotal
if $V and $V > 127 1 137 138
Condition66%2/3
$V and $V > 127
!ll&&!rl&&r
01371
MC/DC50%1/2
$V and $V > 127
$V $V > 127
Truth table66%2/3
A and B
A= $VB= $V > 127
ABresult
0X0
100
111
2854 138 ▶ $V && $V < 1_114_111 && $V != 65535 && !($V > 55295 && $V < 57344) ? chr($V) : "";
Branch: 1 branch
BranchTrueFalseTotal
$V && $V < 1114111 && $V != 65535 && !($V > 55295 && $V < 57344) ? : 138 0 138
Condition33%4/12
$V and $V < 1114111 and $V != 65535 and not $V > 55295 && $V < 57344
!ll&&!rl&&r
00138
$V and $V < 1114111 and $V != 65535
!ll&&!rl&&r
00138
$V and $V < 1114111
!ll&&!rl&&r
00138
$V > 55295 && $V < 57344
!ll&&!rl&&r
13800
MC/DC0%0/5
$V and $V < 1114111 and $V != 65535 and not $V > 55295 && $V < 57344
$V $V < 1114111 $V != 65535 $V > 55295 $V < 57344
Truth table16%1/6
A and B and C and not(D && E)
A= $VB= $V < 1114111C= $V != 65535D= $V > 55295E= $V < 57344
ABCDEresult
0XXXX0
10XXX0
110XX0
111110
1110X1
111101
2855 }egi;
2856  
2857 # These get requoted when we output the attribute
2858 736 ▶ $AttrVal =~ s/&(quot|apos|amp|lt|gt);?/$EntityToChar{lc($1)} || warn "no entity for: $1"/egi;
Condition50%1/2
$EntityToChar{lc $1} || warn("no entity for: $1")
l!l
130
MC/DC0%0/1
$EntityToChar{lc $1} || warn("no entity for: $1")
$EntityToChar{lc $1}
Truth table50%1/2
A
A= $EntityToChar{lc $1}
Aresult
11
00
2859  
2860 # Have to upgrade string to unicode string if entity expansion
2861 # resulted in non-ascii char
2862 736 ▶ utf8::upgrade($AttrVal) if $UnicodeEntity;
Branch: 1 branch
BranchTrueFalseTotal
if $UnicodeEntity 1 735 736
2863  
2864 736 ▶ warn "cleanup_attribute AttrVal=$AttrVal" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 736 736
2865 736 return $AttrVal;
2866 }
2867  
2868 764 ▶sub strip_attribute {
Subroutine strip_attribute: called CC=6 SCAR=28.6
Pod undocumented
2869 764 my ($Self, $AttrVal) = @_;
2870  
2871 # In JS, \u000a is unicode char (note &#x5c;&#x75;&#x30;&#x30;&#x37;&#x32; -> \u0072 -> r, so do HTML entities first)
2872 # This can't be undone, so only do on stripped value
2873 0 ▶ $AttrVal =~ s/\\u(0?[\da-f]{1,6});?/defined($1) && hex($1) < 1_114_111 && hex($1) != 65535 && !(hex($1) > 55295 && hex($1) < 57344) ? chr(hex($1)) : ""/egi;
Branch: 1 branch
BranchTrueFalseTotal
defined $1 && hex $1 < 1114111 && hex $1 != 65535 && !(hex $1 > 55295 && hex $1 < 57344) ? : 0 0 0
Condition0%0/12
defined $1 and hex $1 < 1114111 and hex $1 != 65535 and not hex $1 > 55295 && hex $1 < 57344
!ll&&!rl&&r
000
defined $1 and hex $1 < 1114111 and hex $1 != 65535
!ll&&!rl&&r
000
defined $1 and hex $1 < 1114111
!ll&&!rl&&r
000
hex $1 > 55295 && hex $1 < 57344
!ll&&!rl&&r
000
MC/DC0%0/5
defined $1 and hex $1 < 1114111 and hex $1 != 65535 and not hex $1 > 55295 && hex $1 < 57344
defined $1 hex $1 < 1114111 hex $1 != 65535 hex $1 > 55295 hex $1 < 57344
Truth table0%0/6
A and B and C and not(D && E)
A= defined $1B= hex $1 < 1114111C= hex $1 != 65535D= hex $1 > 55295E= hex $1 < 57344
ABCDEresult
0XXXX0
10XXX0
110XX0
111110
1110X1
111101
2874  
2875 # Also undo URL decoding for "stripped" value
2876 # (can't do this above, because it's non-reversible, eg "http://...?a=%25" => "http://...?a=?",
2877 # how would we know which ? to requote when outputting?)
2878 764 $AttrVal =~ s/%([\da-f]{2})/chr(hex($1))/egi;
2879 764 $AttrVal =~ s/[\x00-\x19]+//g;
2880 764 $AttrVal =~ s/^[\x20]+//g; # http://ha.ckers.org/xss.html#XSS_Spaces_meta_chars
2881  
2882 764 return $AttrVal;
2883 }
2884  
2885 0 ▶sub get_applicable_charset {
Subroutine get_applicable_charset: not called CC=9 SCAR=45.0
Pod undocumented
2886  
2887 0 my $Self = shift;
2888 0 local $_ = shift;
2889 0 my $Charset = shift;
2890  
2891 0 ▶ if(!$Charset) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($Charset) 0 0 0
2892 # Look for <meta> tags
2893 0 my @MetaAttrs = /<meta[\s\/]+(${AttributesRE})/gi;
2894  
2895 0 for(@MetaAttrs) {
2896 0 my %Attrs;
2897  
2898 # Get attributes and their values
2899 0 ▶ while(s/(?:($AttrKeyStartLineRE)(\s*))?(?:(=\s*)($AttrValRE)(\s*))?//so) {
Branch: 1 branch
BranchTrueFalseTotal
if (s/(?:($AttrKeyStartLineRE)(\s*))?(?:(=\s*)($AttrValRE)(\s*))?//os) 0 0 0
2900 0 ▶ last if !defined($1) && !defined($4);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $1 or defined $4 0 0 0
Condition0%0/3
defined $1 or defined $4
l!l&&r!l&&!r
000
MC/DC0%0/2
defined $1 or defined $4
defined $1 defined $4
Truth table0%0/3
A or B
A= defined $1B= defined $4
ABresult
1X1
011
000
2901 0 $Attrs{lc $1} = $4;
2902 }
2903  
2904 # Look for charset information
2905 0 ▶ if($Attrs{"content"}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Attrs{"content"}) 0 0 0
2906 0 ▶ $Charset = $Attrs{"content"} =~ m/charset\s*=\s*([^\s;'"`]+)[\s;'"`]*/i ? $1 : $Charset;
Branch: 1 branch
BranchTrueFalseTotal
$Attrs{'content'} =~ /charset\s*=\s*([^\s;'"`]+)[\s;'"`]*/i ? : 0 0 0
2907 }
2908 }
2909 }
2910  
2911 # Return fallback charset if no header or meta charset found
2912 0 ▶ return $Charset ? $Charset : shift;
Branch: 1 branch
BranchTrueFalseTotal
$Charset ? : 0 0 0
2913 }
2914  
2915 =head1 SEE ALSO
2916  
2917 L<http://mailtools.anomy.net/>, L<http://htmlcleaner.sourceforge.net/>, I<HTML::StripScripts>, I<HTML::Detoxifier>, I<HTML::Sanitizer>, I<HTML::Scrubber>
2918  
2919 =cut
2920  
2921 =head1 AUTHOR
2922  
2923 Kurian Jose Aerthail E<lt>cpan@kurianja.fastmail.fmE<gt>. Thanks to Rob Mueller E<lt>cpan@robm.fastmail.fmE<gt> for initial code, guidance and support and bug fixes.
2924  
2925 =cut
2926  
2927 =head1 COPYRIGHT AND LICENSE
2928  
2929 Copyright (C) 2003-2013 by FastMail Pty Ltd
2930  
2931 This library is free software; you can redistribute it and/or modify
2932 it under the same terms as Perl itself.
2933  
2934 =cut
2935  
2936 11 1;
2937  
↑ Summary