lib/CSS/Inliner.pm

filter: Statementstmt 64.9% 270 / 416 Branchbran 46.3% 75 / 162 Conditioncond 27.9% 43 / 154 MC/DCmcdc 8.0% 7 / 87 Subroutinesub 82.0% 32 / 39 Podpod 100% 10 / 10 totaltotal 50.3% 437 / 868 CC 150 SCAR 43.6
CC
150
Cov
53%
__changelink_relative
462.0
__expand_stylesheet
110.0
_validate_html
77.1
CRAP 78.3
↑ Summary blib/lib/CSS/Inliner.pm »
1 package CSS::Inliner;
2 26 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 26 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 26 our $VERSION = '4014';
6  
7 26 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 26 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 26 ▶use LWP::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 26 ▶use HTML::Query 'query';
Subroutine BEGIN: called CC=1 SCAR=0.0
11 26 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 26 ▶use CSS::Inliner::Parser;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 26 ▶use CSS::Inliner::TreeBuilder;
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 =pod
17  
18 =head1 NAME
19  
20 CSS::Inliner - Library for converting CSS <style> blocks to inline styles.
21  
22 =head1 SYNOPSIS
23  
24 use CSS::Inliner;
25  
26 my $inliner = new CSS::Inliner();
27  
28 $inliner->read_file({ filename => 'myfile.html' });
29  
30 print $inliner->inlinify();
31  
32 =head1 DESCRIPTION
33  
34 Library for converting CSS style blocks into inline styles in an HTML
35 document. Specifically this is intended for the ease of generating
36 HTML emails. This is useful as certain email clients don't support top
37 level <style> declarations despite it being 2017.
38  
39 NOTE: The development of the this module is currently suspended as the
40 sponsoring entity, MailerMailer LLC, has been sold to j2 Global.
41  
42 =cut
43  
44 BEGIN {
45 26 ▶ my $members = ['stylesheet','css','html','html_tree','query','strip_attrs','relaxed','leave_style','warns_as_errors','content_warnings','agent','fixlatin'];
Subroutine BEGIN: called CC=2 SCAR=6.9
46  
47 #generate all the getter/setter we need
48 26 foreach my $member (@{$members}) {
49 26 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
50  
51 312 *{'_' . $member} = sub {
52 1644 ▶ my ($self,$value) = @_;
Subroutine __ANON__: called CC=2 SCAR=6.9
53  
54 1644 $self->_check_object();
55  
56 1644 ▶ $self->{$member} = $value if defined($value);
Branch: 1 branch
BranchTrueFalseTotal
if defined $value 81 1563 1644
57  
58 1644 return $self->{$member};
59 }
60 312 }
61 }
62  
63 =head1 METHODS
64  
65 =head2 new
66  
67 Instantiates the Inliner object. Sets up class variables that are used
68 during file parsing/processing. Possible options are:
69  
70 html_tree - (optional) Pass in a fresh unparsed instance of HTML::Treebuilder
71  
72 NOTE: Any passed references to HTML::TreeBuilder will be substantially altered by passing it in here...
73  
74 strip_attrs - (optional) Remove all "id" and "class" attributes during inlining
75  
76 leave_style - (optional) Leave style/link tags alone within <head> during inlining
77  
78 relaxed - (optional) Relaxed HTML parsing which will attempt to interpret non-HTML4 documents.
79  
80 NOTE: This argument is not compatible with passing an html_tree.
81  
82 agent - (optional) Pass in a string containing a preferred user-agent, overrides the internal default provided by the module for handling remote documents
83  
84 =cut
85  
86 sub new {
87 28 ▶ my ($proto, $params) = @_;
Subroutine new: called CC=21 SCAR=37.5
Pod documented
88  
89 28 ▶ my $class = ref($proto) || $proto;
Condition33%1/3
ref $proto || $proto
l!l&&r!l&&!r
0280
MC/DC0%0/2
ref $proto || $proto
ref $proto $proto
Truth table33%1/3
A || B
A= ref $protoB= $proto
ABresult
1X1
011
000
90  
91 # passed in html_tree argument must be of correct type
92 # TODO: make sure tree has no content already
93 28 ▶ if (defined $$params{html_tree} && $$params{html_tree} && ref $$params{html_tree} ne 'HTML::TreeBuilder') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params->{"html_tree"} and $params->{"html_tree"} and ref $params->{"html_tree"} ne "HTML::TreeBuilder") 0 28 28
Condition66%4/6
defined $params->{"html_tree"} and $params->{"html_tree"} and ref $params->{"html_tree"} ne "HTML::TreeBuilder"
!ll&&!rl&&r
2620
defined $params->{"html_tree"} and $params->{"html_tree"}
!ll&&!rl&&r
2602
MC/DC0%0/3
defined $params->{"html_tree"} and $params->{"html_tree"} and ref $params->{"html_tree"} ne "HTML::TreeBuilder"
defined $params->{"html_tree"} $params->{"html_tree"} ref $params->{"html_tree"} ne "HTML::TreeBuilder"
Truth table50%2/4
A and B and C
A= defined $params->{"html_tree"}B= $params->{"html_tree"}C= ref $params->{"html_tree"} ne "HTML::TreeBuilder"
ABCresult
0XX0
10X0
1100
1111
94 0 croak 'Incompatible argument passed to new: "html_tree"';
95 }
96  
97 # check to make sure caller is not trying to pass both an html_tree and setting relaxed flag
98 # relaxed flag requires our own internal TreeBuilder, not HTML::TreeBuilder
99 28 ▶ if (defined $$params{html_tree} && $$params{html_tree} && defined $$params{relaxed} && $$params{relaxed}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params->{"html_tree"} and $params->{"html_tree"} and defined $params->{"relaxed"} and $params->{"relaxed"}) 0 28 28
Condition55%5/9
defined $params->{"html_tree"} and $params->{"html_tree"} and defined $params->{"relaxed"} and $params->{"relaxed"}
!ll&&!rl&&r
2800
defined $params->{"html_tree"} and $params->{"html_tree"} and defined $params->{"relaxed"}
!ll&&!rl&&r
2620
defined $params->{"html_tree"} and $params->{"html_tree"}
!ll&&!rl&&r
2602
MC/DC0%0/4
defined $params->{"html_tree"} and $params->{"html_tree"} and defined $params->{"relaxed"} and $params->{"relaxed"}
defined $params->{"html_tree"} $params->{"html_tree"} defined $params->{"relaxed"} $params->{"relaxed"}
Truth table40%2/5
A and B and C and D
A= defined $params->{"html_tree"}B= $params->{"html_tree"}C= defined $params->{"relaxed"}D= $params->{"relaxed"}
ABCDresult
0XXX0
10XX0
110X0
11100
11111
100 0 croak 'Incompatible argument passed to new: "html_tree"';
101 }
102  
103 my $self = {
104 stylesheet => undef,
105 css => CSS::Inliner::Parser->new({ warns_as_errors => $$params{warns_as_errors} }),
106 html => undef,
107 html_tree => defined($$params{html_tree}) ? $$params{html_tree} : CSS::Inliner::TreeBuilder->new(),
108 query => undef,
109 content_warnings => {},
110 strip_attrs => (defined($$params{strip_attrs}) && $$params{strip_attrs}) ? 1 : 0,
111 relaxed => (defined($$params{relaxed}) && $$params{relaxed}) ? 1 : 0,
112 leave_style => (defined($$params{leave_style}) && $$params{leave_style}) ? 1 : 0,
113 warns_as_errors => (defined($$params{warns_as_errors}) && $$params{warns_as_errors}) ? 1 : 0,
114 agent => (defined($$params{agent}) && $$params{agent}) ? $$params{agent} : 'Mozilla/4.0',
115 28 ▶ fixlatin => eval { require Encoding::FixLatin; return 1; } ? 1 : 0
Branch: 7 branches
BranchTrueFalseTotal
defined $params->{'html_tree'} ? : 2 26 28
defined $params->{'strip_attrs'} && $params->{'strip_attrs'} ? : 2 26 28
defined $params->{'relaxed'} && $params->{'relaxed'} ? : 1 27 28
defined $params->{'leave_style'} && $params->{'leave_style'} ? : 3 25 28
defined $params->{'warns_as_errors'} && $params->{'warns_as_errors'} ? : 0 28 28
defined $params->{'agent'} && $params->{'agent'} ? : 0 28 28
eval { do { require Encoding::FixLatin; return 1 } } ? : 0 28 28
Condition53%8/15
defined $params->{"strip_attrs"} and $params->{"strip_attrs"}
!ll&&!rl&&r
2602
defined $params->{"relaxed"} and $params->{"relaxed"}
!ll&&!rl&&r
2701
defined $params->{"leave_style"} and $params->{"leave_style"}
!ll&&!rl&&r
2503
defined $params->{"warns_as_errors"} and $params->{"warns_as_errors"}
!ll&&!rl&&r
2800
defined $params->{"agent"} and $params->{"agent"}
!ll&&!rl&&r
2800
MC/DC50%1/2
defined $params->{"strip_attrs"} and $params->{"strip_attrs"}
defined $params->{"strip_attrs"} $params->{"strip_attrs"}
MC/DC50%1/2
defined $params->{"relaxed"} and $params->{"relaxed"}
defined $params->{"relaxed"} $params->{"relaxed"}
MC/DC50%1/2
defined $params->{"leave_style"} and $params->{"leave_style"}
defined $params->{"leave_style"} $params->{"leave_style"}
MC/DC0%0/2
defined $params->{"warns_as_errors"} and $params->{"warns_as_errors"}
defined $params->{"warns_as_errors"} $params->{"warns_as_errors"}
MC/DC0%0/2
defined $params->{"agent"} and $params->{"agent"}
defined $params->{"agent"} $params->{"agent"}
Truth table66%2/3
A and B
A= defined $params->{"strip_attrs"}B= $params->{"strip_attrs"}
ABresult
0X0
100
111
Truth table66%2/3
A and B
A= defined $params->{"relaxed"}B= $params->{"relaxed"}
ABresult
0X0
100
111
Truth table66%2/3
A and B
A= defined $params->{"leave_style"}B= $params->{"leave_style"}
ABresult
0X0
100
111
Truth table33%1/3
A and B
A= defined $params->{"warns_as_errors"}B= $params->{"warns_as_errors"}
ABresult
0X0
100
111
Truth table33%1/3
A and B
A= defined $params->{"agent"}B= $params->{"agent"}
ABresult
0X0
100
111
116 };
117  
118 28 bless $self, $class;
119  
120 28 $self->_configure_tree({ tree => $self->_html_tree });
121  
122 28 return $self;
123 }
124  
125 =head2 fetch_file
126  
127 Fetches a remote HTML file that supposedly contains both HTML and a
128 style declaration, properly tags the data with the proper charset
129 as provided by the remote webserver (if any). Subsequently calls the
130 read method automatically.
131  
132 This method expands all relative urls, as well as fully expands the
133 stylesheet reference within the document.
134  
135 This method requires you to pass in a params hash that contains a
136 url argument for the requested document. For example:
137  
138 $self->fetch_file({ url => 'http://www.example.com' });
139  
140 Note that you can specify a user-agent to override the default user-agent
141 of 'Mozilla/4.0' within the constructor. Doing so may avoid certain issues
142 with agent filtering related to quirky webserver configs.
143  
144 Input Parameters:
145 url - the desired url for a remote asset presumably containing both html and css
146 charset - (optional) programmer specified charset for the pass url
147  
148 =cut
149  
150 sub fetch_file {
151 1 ▶ my ($self,$params) = @_;
Subroutine fetch_file: called CC=5 SCAR=27.7
Pod documented
152  
153 1 $self->_check_object();
154  
155 1 ▶ unless ($params && $$params{url}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($params and $params->{"url"}) 0 1 1
Condition33%1/3
$params and $params->{"url"}
!ll&&!rl&&r
001
MC/DC0%0/2
$params and $params->{"url"}
$params $params->{"url"}
Truth table33%1/3
A and B
A= $paramsB= $params->{"url"}
ABresult
0X0
100
111
156 0 croak 'You must pass in hash params that contain a url argument';
157 }
158  
159 # fetch and retrieve the remote content
160 1 my ($content,$baseref,$ctcharset) = $self->_fetch_url({ url => $$params{url} });
161  
162 0 my $charset = $self->detect_charset({ content => $content, charset => $$params{charset}, ctcharset => $ctcharset });
163  
164 0 my $decoded_html;
165 0 ▶ if ($charset) {
Branch: 1 branch
BranchTrueFalseTotal
if ($charset) { } 0 0 0
166 0 $decoded_html = $self->decode_characters({ content => $content, charset => $charset });
167 }
168 else {
169 # no good hints found, do the best we can
170  
171 0 ▶ if ($self->_fixlatin()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_fixlatin) { } 0 0 0
172 0 Encoding::FixLatin->import('fix_latin');
173 0 $decoded_html = fix_latin($content);
174 }
175 else {
176 0 $decoded_html = $self->decode_characters({ content => $content, charset => 'ascii' });
177 }
178 }
179  
180 0 my $html = $self->_absolutize_references({ content => $decoded_html, baseref => $baseref });
181  
182 0 $self->read({ html => $html, charset => $charset });
183  
184 0 return();
185 }
186  
187 =head2 read_file
188  
189 Opens and reads an HTML file that supposedly contains both HTML and a
190 style declaration, properly tags the data with the proper charset
191 if specified. It subsequently calls the read() method automatically.
192  
193 This method requires you to pass in a params hash that contains a
194 filename argument. For example:
195  
196 $self->read_file({ filename => 'myfile.html' });
197  
198 Additionally you can specify the character encoding within the file, for
199 example:
200  
201 $self->read_file({ filename => 'myfile.html', charset => 'utf8' });
202  
203 Input Parameters:
204 filename - name of local file presumably containing both html and css
205 charset - (optional) programmer specified charset of the passed file
206  
207 =cut
208  
209 sub read_file {
210 1 ▶ my ($self,$params) = @_;
Subroutine read_file: called CC=6 SCAR=21.5
Pod documented
211  
212 1 $self->_check_object();
213  
214 1 ▶ unless ($params && $$params{filename}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($params and $params->{"filename"}) 0 1 1
Condition33%1/3
$params and $params->{"filename"}
!ll&&!rl&&r
001
MC/DC0%0/2
$params and $params->{"filename"}
$params $params->{"filename"}
Truth table33%1/3
A and B
A= $paramsB= $params->{"filename"}
ABresult
0X0
100
111
215 0 croak "You must pass in hash params that contain a filename argument";
216 }
217  
218 1 ▶ open FILE, "<", $$params{filename} or die $!;
Branch: 1 branch
BranchTrueFalseTotal
open FILE, "<", $params->{"filename"} or die $! 0 1 1
219 1 my $content = do { local( $/ ) ; <FILE> };
220  
221 1 my $charset = $self->detect_charset({ content => $content, charset => $$params{charset} });
222  
223 1 my $decoded_html;
224 1 ▶ if ($charset) {
Branch: 1 branch
BranchTrueFalseTotal
if ($charset) { } 1 0 1
225 1 $decoded_html = $self->decode_characters({ content => $content, charset => $charset });
226 }
227 else {
228 # no good hints found, do the best we can
229  
230 0 ▶ if ($self->_fixlatin()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_fixlatin) { } 0 0 0
231 0 Encoding::FixLatin->import('fix_latin');
232 0 $decoded_html = fix_latin($content);
233 }
234 else {
235 0 $decoded_html = $self->decode_characters({ content => $content, charset => 'ascii' });
236 }
237 }
238  
239 1 $self->read({ html => $decoded_html, charset => $charset });
240  
241 1 return();
242 }
243  
244 =head2 read
245  
246 Reads passed html data and parses it. The intermediate data is stored in
247 class variables.
248  
249 The <style> block is ripped out of the html here, and stored
250 separately. Class/ID/Names used in the markup are left alone.
251  
252 This method requires you to pass in a params hash that contains scalar
253 html data. For example:
254  
255 $self->read({ html => $html });
256  
257 NOTE: You are required to pass a properly encoded perl reference to the
258 html data. This method does *not* do the dirty work of encoding the html
259 as utf8 - do that before calling this method.
260  
261 Input Parameters:
262 html - scalar presumably containing both html and css
263 charset - (optional) scalar representing the original charset of the passed html
264  
265 =cut
266  
267 sub read {
268 27 ▶ my ($self,$params) = @_;
Subroutine read: called CC=6 SCAR=19.7
Pod documented
269  
270 27 $self->_check_object();
271  
272 27 ▶ unless ($params && $$params{html}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($params and $params->{"html"}) 0 27 27
Condition33%1/3
$params and $params->{"html"}
!ll&&!rl&&r
0027
MC/DC0%0/2
$params and $params->{"html"}
$params $params->{"html"}
Truth table33%1/3
A and B
A= $paramsB= $params->{"html"}
ABresult
0X0
100
111
273 0 croak 'You must pass in hash params that contains html data';
274 }
275  
276 27 ▶ if ($params && $$params{charset} && !find_encoding($$params{charset})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params and $params->{"charset"} and not &find_encoding($params->{"charset"})) 0 27 27
Condition66%4/6
$params and $params->{"charset"} and not &find_encoding($params->{"charset"})
!ll&&!rl&&r
2610
$params and $params->{"charset"}
!ll&&!rl&&r
0261
MC/DC0%0/3
$params and $params->{"charset"} and not &find_encoding($params->{"charset"})
$params $params->{"charset"} not &find_encoding($params->{"charset"})
Truth table50%2/4
A and B and not(C)
A= $paramsB= $params->{"charset"}C= not &find_encoding($params->{"charset"})
ABCresult
0XX0
10X0
1100
1111
277 0 croak "Invalid charset passed to read()";
278 }
279  
280 27 $self->_html_tree->parse_content($$params{html});
281  
282 27 $self->_init_query();
283  
284 #suck in the styles for later use from the head section - stylesheets anywhere else are invalid
285 27 my $stylesheet = $self->_parse_stylesheet();
286  
287 #save the data
288 27 $self->_html($$params{html});
289 27 $self->_stylesheet($stylesheet);
290  
291 27 return();
292 }
293  
294 =head2 detect_charset
295  
296 Detect the charset of the passed content.
297  
298 The algorithm present here is roughly based off of the HTML5 W3C working group document,
299 which lays out a recommendation for determining the character set of a received document, which
300 can be seen here under the "determining the character encoding" section:
301 http://www.w3.org/TR/html5/syntax.html
302  
303 NOTE: In the event that no charset can be identified the library will handle the content as a mix of
304 UTF-8/CP-1252/8859-1/ASCII by attempting to use the Encoding::FixLatin module, as this combination
305 is relatively common in the wild. Finally, if Encoding::FixLatin is unavailable the content will be
306 treated as ASCII.
307  
308 Input Parameters:
309 content - scalar presumably containing both html and css
310 charset - (optional) programmer specified charset for the passed content
311 ctcharset - (optional) content-type specified charset for content retrieved via a url
312  
313 =cut
314  
315 sub detect_charset {
316 1 ▶ my ($self,$params) = @_;
Subroutine detect_charset: called CC=11 SCAR=39.1
Pod documented
317  
318 1 $self->_check_object();
319  
320 1 ▶ unless ($params && $$params{content}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($params and $params->{"content"}) 0 1 1
Condition33%1/3
$params and $params->{"content"}
!ll&&!rl&&r
001
MC/DC0%0/2
$params and $params->{"content"}
$params $params->{"content"}
Truth table33%1/3
A and B
A= $paramsB= $params->{"content"}
ABresult
0X0
100
111
321 0 croak "You must pass content for content character decoding";
322 }
323  
324 1 my $charset;
325 1 ▶ if (exists($$params{charset}) && $$params{charset} && find_encoding($$params{charset})) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $params->{'charset'} and $params->{'charset'} and &find_encoding($params->{'charset'})) { } 1 0 1
elsif (exists $params->{'ctcharset'} and $params->{'ctcharset'} and &find_encoding($params->{'ctcharset'})) { } 0 0 0
Condition33%2/6
exists $params->{"charset"} and $params->{"charset"} and &find_encoding($params->{"charset"})
!ll&&!rl&&r
001
exists $params->{"charset"} and $params->{"charset"}
!ll&&!rl&&r
001
MC/DC0%0/3
exists $params->{"charset"} and $params->{"charset"} and &find_encoding($params->{"charset"})
exists $params->{"charset"} $params->{"charset"} &find_encoding($params->{"charset"})
Truth table25%1/4
A and B and C
A= exists $params->{"charset"}B= $params->{"charset"}C= &find_encoding($params->{"charset"})
ABCresult
0XX0
10X0
1100
1111
326 # precedence given to programmer provided charset
327 1 $charset = $$params{charset};
328 }
329 ▶ elsif (exists($$params{ctcharset}) && $$params{ctcharset} && find_encoding($$params{ctcharset})) {
Condition0%0/6
exists $params->{"ctcharset"} and $params->{"ctcharset"} and &find_encoding($params->{"ctcharset"})
!ll&&!rl&&r
000
exists $params->{"ctcharset"} and $params->{"ctcharset"}
!ll&&!rl&&r
000
MC/DC0%0/3
exists $params->{"ctcharset"} and $params->{"ctcharset"} and &find_encoding($params->{"ctcharset"})
exists $params->{"ctcharset"} $params->{"ctcharset"} &find_encoding($params->{"ctcharset"})
Truth table0%0/4
A and B and C
A= exists $params->{"ctcharset"}B= $params->{"ctcharset"}C= &find_encoding($params->{"ctcharset"})
ABCresult
0XX0
10X0
1100
1111
330 # use the Content-Type charset if available
331 0 $charset = $$params{ctcharset};
332 }
333 else {
334 # analyze the document to scan for any meta charset hints we can use
335 0 my $meta_charset = $self->_extract_meta_charset({ content => $$params{content} });
336  
337 0 ▶ if ($meta_charset && find_encoding($meta_charset)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($meta_charset and &find_encoding($meta_charset)) { } 0 0 0
Condition0%0/3
$meta_charset and &find_encoding($meta_charset)
!ll&&!rl&&r
000
MC/DC0%0/2
$meta_charset and &find_encoding($meta_charset)
$meta_charset &find_encoding($meta_charset)
Truth table0%0/3
A and B
A= $meta_charsetB= &find_encoding($meta_charset)
ABresult
0X0
100
111
338 # use the meta charset from the document if available
339 0 $charset = $meta_charset;
340 }
341 else {
342 # no hints found...
343 }
344 }
345  
346 1 return $charset;
347 }
348  
349 =head2 decode_characters
350  
351 Implement the character decoding algorithm for HTML as outlined by the various working groups
352  
353 Basically apply best practices for determining the applied character encoding and properly decode it
354  
355 It is expected that this method will be called before any calls to read()
356  
357 Input Parameters:
358 content - scalar presumably containing both html and css
359 charset - known charset for the passed content
360  
361 =cut
362  
363 sub decode_characters {
364 1 ▶ my ($self,$params) = @_;
Subroutine decode_characters: called CC=6 SCAR=20.9
Pod documented
365  
366 1 $self->_check_object();
367  
368 1 ▶ unless ($params && $$params{content}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($params and $params->{"content"}) 0 1 1
Condition33%1/3
$params and $params->{"content"}
!ll&&!rl&&r
001
MC/DC0%0/2
$params and $params->{"content"}
$params $params->{"content"}
Truth table33%1/3
A and B
A= $paramsB= $params->{"content"}
ABresult
0X0
100
111
369 0 croak "You must pass content for content character decoding";
370 }
371  
372 1 ▶ unless ($params && $$params{charset}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($params and $params->{"charset"}) 0 1 1
Condition33%1/3
$params and $params->{"charset"}
!ll&&!rl&&r
001
MC/DC0%0/2
$params and $params->{"charset"}
$params $params->{"charset"}
Truth table33%1/3
A and B
A= $paramsB= $params->{"charset"}
ABresult
0X0
100
111
373 0 croak "You must pass the charset type of the content to decode";
374 }
375  
376 1 my $content = $$params{content};
377 1 my $charset = $$params{charset};
378  
379 1 my $decoded_html;
380 1 eval {
381 1 $decoded_html = decode($charset,$content);
382 };
383  
384 1 ▶ if (!$decoded_html) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($decoded_html) 0 1 1
385 0 croak('Error decoding content with character set "'.$$params{charset}.'"');
386 }
387  
388 1 return $decoded_html;
389 }
390  
391 =head2 inlinify
392  
393 Processes the html data that was entered through either 'read' or
394 'read_file', returns a scalar that contains a composite chunk of html
395 that has inline styles instead of a top level <style> declaration.
396  
397 =cut
398  
399 sub inlinify {
400 27 ▶ my ($self,$params) = @_;
Subroutine inlinify: called CC=18 SCAR=29.6
Pod documented
401  
402 27 $self->_check_object();
403  
404 27 $self->_content_warnings({}); # overwrite any existing warnings
405  
406 27 ▶ unless ($self->_html() && $self->_html_tree()) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_html and $self->_html_tree) 0 27 27
Condition33%1/3
$self->_html and $self->_html_tree
!ll&&!rl&&r
0027
MC/DC0%0/2
$self->_html and $self->_html_tree
$self->_html $self->_html_tree
Truth table33%1/3
A and B
A= $self->_htmlB= $self->_html_tree
ABresult
0X0
100
111
407 0 croak 'You must instantiate and read in your content before inlinifying';
408 }
409  
410 # perform a check to see how bad this html is...
411 27 $self->_validate_html({ html => $self->_html() });
412  
413 27 my $html;
414 27 ▶ if (defined $self->_css()) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->_css) { } 27 0 27
415 #parse and store the stylesheet as a hash object
416  
417 27 $self->_css->read({ css => $self->_stylesheet() });
418  
419 27 my @css_warnings = @{$self->_css->content_warnings()};
420 27 foreach my $css_warning (@css_warnings) {
421 1 $self->_report_warning({ info => $css_warning });
422 }
423  
424 27 my %matched_elements;
425 27 my $count = 0;
426  
427 27 foreach my $entry (@{$self->_css->get_rules()}) {
428 184 ▶ next unless exists $$entry{selector} && $$entry{declarations};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $entry->{"selector"} and $entry->{"declarations"} 11 173 184
Condition66%2/3
exists $entry->{"selector"} and $entry->{"declarations"}
!ll&&!rl&&r
110173
MC/DC50%1/2
exists $entry->{"selector"} and $entry->{"declarations"}
exists $entry->{"selector"} $entry->{"declarations"}
Truth table66%2/3
A and B
A= exists $entry->{"selector"}B= $entry->{"declarations"}
ABresult
0X0
100
111
429  
430 173 my $selector = $$entry{selector};
431 173 my $declarations = $$entry{declarations};
432  
433 #skip over the following pseudo selectors, these particular ones are not inlineable
434 173 ▶ if ($selector =~ /(?:^|[\w\._\*\]])::?(?:([\w\-]+))\b/io && $1 !~ /first-child|last-child/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($selector =~ /(?:^|[\w\._\*\]])::?(?:([\w\-]+))\b/io and not $1 =~ /first-child|last-child/i) 38 135 173
Condition66%2/3
$selector =~ /(?:^|[\w\._\*\]])::?(?:([\w\-]+))\b/io and not $1 =~ /first-child|last-child/i
!ll&&!rl&&r
135038
MC/DC50%1/2
$selector =~ /(?:^|[\w\._\*\]])::?(?:([\w\-]+))\b/io and not $1 =~ /first-child|last-child/i
$selector =~ /(?:^|[\w\._\*\]])::?(?:([\w\-]+))\b/io not $1 =~ /first-child|last-child/i
Truth table66%2/3
A and not(B)
A= $selector =~ /(?:^|[\w\._\*\]])::?(?:([\w\-]+))\b/ioB= not $1 =~ /first-child|last-child/i
ABresult
0X0
100
111
435 38 $self->_report_warning({ info => "The pseudo-class ':$1' cannot be supported inline" });
436 38 next;
437 }
438  
439 #skip over @import or anything else that might start with @ - not inlineable
440 135 ▶ if ($selector =~ /^\@/io) {
Branch: 1 branch
BranchTrueFalseTotal
if ($selector =~ /^\@/io) 0 135 135
441 0 $self->_report_warning({ info => "The directive '$selector' cannot be supported inline" });
442 0 next;
443 }
444  
445 135 my $query_result;
446  
447 #check to see if query fails, possible for jacked selectors
448 135 eval {
449 135 $query_result = $self->query({ selector => $selector });
450 };
451  
452 135 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 135 135
453 0 $self->_report_warning({ info => $@->info() });
454 0 next;
455 }
456  
457 # CSS rules cascade based on the specificity and order
458 135 my $specificity = $self->specificity({ selector => $selector });
459  
460 #if an element matched a style within the document store the rule, the specificity
461 #and the actually CSS attributes so we can inline it later
462 135 foreach my $element (@{$query_result->get_elements()}) {
463  
464 275 ▶ $matched_elements{$element->address()} ||= [];
Condition100%2/2
$matched_elements{$element->address} ||= []
l!l
102173
MC/DC100%1/1
$matched_elements{$element->address} ||= []
$matched_elements{$element->address}
Truth table100%2/2
A
A= $matched_elements{$element->address}
Aresult
11
00
465 275 my %match_info = (
466 rule => $selector,
467 element => $element,
468 specificity => $specificity,
469 position => $count,
470 css => $declarations
471 );
472  
473 275 push(@{$matched_elements{$element->address()}}, \%match_info);
474 275 $count++;
475 }
476 }
477  
478 #process all elements
479 27 foreach my $matches (values %matched_elements) {
480 173 my $element = $matches->[0]->{element};
481 # rules are sorted by specificity, and if there's a tie the position is used
482 # we sort with the lightest items first so that heavier items can override later
483 173 ▶ my @sorted_matches = sort { $a->{specificity} <=> $b->{specificity} || $a->{position} <=> $b->{position} } @$matches;
Branch: 1 branch
BranchTrueFalseTotal
$CSS::Inliner::a->{"specificity"} <=> $CSS::Inliner::b->{"specificity"} or $CSS::Inliner::a->{"position"} <=> $CSS::Inliner::b->{"position"} 41 95 136
484  
485 173 my %new_style;
486 my %new_important_style;
487  
488 173 foreach my $match (@sorted_matches) {
489 275 %new_style = (%new_style, %{$match->{css}});
490 275 %new_important_style = (%new_important_style, _grep_important_declarations($match->{css}));
491 }
492  
493 # styles already inlined have greater precedence
494 173 ▶ if (defined($element->attr('style'))) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $element->attr("style")) 8 165 173
495 8 my $cur_style = $self->_split({ style => $element->attr('style') });
496 8 %new_style = (%new_style, %{$cur_style});
497 8 %new_important_style = (%new_important_style, _grep_important_declarations($cur_style));
498 }
499  
500 # override styles with !important styles
501 173 %new_style = (%new_style, %new_important_style);
502  
503 173 $element->attr('style', $self->_expand({ declarations => \%new_style }));
504 }
505  
506 #at this point we have a document that contains the expanded inlined stylesheet
507 #BUT we need to collapse the declarations to remove duplicate overridden styles
508 27 $self->_collapse_inline_styles();
509  
510 # dump out the final processed html for returning to the caller
511 27 $html = $self->_html_tree->as_HTML('',' ',{});
512 }
513 else {
514 0 $html = $self->{html};
515 }
516  
517 27 return $html . "\n";
518 }
519  
520 =head2 query
521  
522 Given a particular selector return back the applicable styles
523  
524 =cut
525  
526 sub query {
527 135 ▶ my ($self,$params) = @_;
Subroutine query: called CC=2 SCAR=7.4
Pod documented
528  
529 135 $self->_check_object();
530  
531 135 ▶ unless ($self->_query()) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_query) 0 135 135
532 0 $self->_init_query();
533 }
534  
535 135 return $self->_query->query($$params{selector});
536 }
537  
538 =head2 specificity
539  
540 Given a particular selector return back the associated selectivity
541  
542 =cut
543  
544 sub specificity {
545 158 ▶ my ($self,$params) = @_;
Subroutine specificity: called CC=2 SCAR=6.9
Pod documented
546  
547 158 $self->_check_object();
548  
549 158 ▶ unless ($self->_query()) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_query) 1 157 158
550 1 $self->_init_query();
551 }
552  
553 158 return $self->_query->get_specificity($$params{selector});
554 }
555  
556 =head2 content_warnings
557  
558 Return back any warnings thrown while inlining a given block of content.
559  
560 Note: content warnings are initialized at inlining time, not at read time. In
561 order to receive back content feedback you must perform inlinify first
562  
563 =cut
564  
565 sub content_warnings {
566 0 ▶ my ($self,$params) = @_;
Subroutine content_warnings: not called CC=1 SCAR=6.9
Pod documented
567  
568 0 $self->_check_object();
569  
570 0 my @content_warnings = keys %{$self->_content_warnings()};
571  
572 0 return \@content_warnings;
573 }
574  
575 ####################################################################
576 # #
577 # The following are all private methods and are not for normal use #
578 # I am working to finalize the get/set methods to make them public #
579 # #
580 ####################################################################
581  
582  
583 sub _check_object {
584 2852 ▶ my ($self, $params) = @_;
Subroutine _check_object: called CC=2 SCAR=7.6
585  
586 2852 ▶ unless (ref $self) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $self) 0 2852 2852
587 0 croak 'You must instantiate this class in order to properly use it';
588 }
589  
590 2852 return();
591 }
592  
593 sub _report_warning {
594 40 ▶ my ($self,$params) = @_;
Subroutine _report_warning: called CC=2 SCAR=7.1
595  
596 40 $self->_check_object();
597  
598 40 ▶ if ($self->_warns_as_errors()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_warns_as_errors) { } 0 40 40
599 0 croak $$params{info};
600 }
601 else {
602 40 my $warnings = $self->_content_warnings();
603 40 $$warnings{$$params{info}} = 1;
604 }
605  
606 40 return();
607 }
608  
609 sub _configure_tree {
610 28 ▶ my ($self,$params) = @_;
Subroutine _configure_tree: called CC=2 SCAR=6.9
611  
612 28 $self->_check_object();
613  
614 28 my $tree = $$params{tree};
615  
616 # configure tree
617 28 $tree->store_comments(1);
618 28 $tree->attr_encoded(1);
619 28 $tree->no_expand_entities(1);
620 28 ▶ if ($self->_relaxed()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_relaxed) 1 27 28
621 1 $tree->ignore_unknown(0);
622 1 $tree->implicit_tags(0);
623 }
624  
625 28 return();
626 }
627  
628 sub _fetch_url {
629 1 ▶ my ($self,$params) = @_;
Subroutine _fetch_url: called CC=5 SCAR=21.9
630  
631 1 $self->_check_object();
632  
633 # Create a user agent object
634 1 my $ua = LWP::UserAgent->new;
635  
636 1 $ua->agent($self->_agent()); # masquerade as Mozilla/4.0 unless otherwise specified in the constructor
637 1 $ua->protocols_allowed( ['http','https'] );
638  
639 # set URI internal flag such that leading dot edge-case urls work
640 1 local $URI::ABS_REMOTE_LEADING_DOTS = 1;
641  
642 # Create a request
643 1 my $uri = URI->new($$params{url});
644  
645 1 my $req = HTTP::Request->new('GET', $uri, [ 'Accept' => 'text/html, */*' ]);
646  
647 # Pass request to the user agent and get a response back
648 1 my $res = $ua->request($req);
649  
650 # if not successful
651 1 ▶ if (!$res->is_success()) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($res->is_success) 1 0 1
652 1 croak 'There was an error in fetching the document for ' . $uri . ' : ' . $res->message;
653 }
654  
655 # Is it a HTML document
656 0 ▶ if ($res->content_type ne 'text/html' && $res->content_type ne 'text/css') {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->content_type ne "text/html" and $res->content_type ne "text/css") 0 0 0
Condition0%0/3
$res->content_type ne "text/html" and $res->content_type ne "text/css"
!ll&&!rl&&r
000
MC/DC0%0/2
$res->content_type ne "text/html" and $res->content_type ne "text/css"
$res->content_type ne "text/html" $res->content_type ne "text/css"
Truth table0%0/3
A and B
A= $res->content_type ne "text/html"B= $res->content_type ne "text/css"
ABresult
0X0
100
111
657 0 croak 'The web site address you entered is not an HTML document.';
658 }
659  
660 # record the content, charset and baseref of the response
661 0 my $ctcharset = $res->content_type_charset();
662 0 ▶ my $content = $res->content || '';
Condition0%0/2
$res->content || ''
l!l
00
MC/DC0%0/1
$res->content || ''
$res->content
Truth table0%0/2
A
A= $res->content
Aresult
11
00
663 0 my $baseref = $res->base;
664  
665 0 return ($content,$baseref,$ctcharset);
666 }
667  
668 sub _absolutize_references {
669 0 ▶ my ($self,$params) = @_;
Subroutine _absolutize_references: not called CC=1 SCAR=6.9
670  
671 0 $self->_check_object();
672  
673 # parse the protected document, we need to localize it
674 0 my $absolutize_tree = new CSS::Inliner::TreeBuilder();
675 0 $self->_configure_tree({ tree => $absolutize_tree });
676  
677 0 $absolutize_tree->parse_content($$params{content});
678  
679 # Change relative links to absolute links
680 0 $self->__changelink_relative({ content => $absolutize_tree->content(), baseref => $$params{baseref} });
681  
682 0 $self->__expand_stylesheet({ content => $absolutize_tree, html_baseref => $$params{baseref} });
683  
684 # dump out the final processed html for reading
685 0 my $absolutized_content = $absolutize_tree->as_HTML('',' ',{});
686  
687 0 return $absolutized_content;
688 }
689  
690 sub __changelink_relative {
691 0 ▶ my ($self,$params) = @_;
Subroutine __changelink_relative: not called CC=21 SCAR=61.4
692  
693 0 $self->_check_object();
694  
695 0 my $base = $$params{baseref};
696  
697 0 foreach my $i (@{$$params{content}}) {
698  
699 0 ▶ next unless ref $i eq 'HTML::Element';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $i eq "HTML::Element" 0 0 0
700  
701 0 ▶ if ($i->tag eq 'img' or $i->tag eq 'frame' or $i->tag eq 'input' or $i->tag eq 'script') {
Branch: 4 branches
BranchTrueFalseTotal
if ($i->tag eq 'img' or $i->tag eq 'frame' or $i->tag eq 'input' or $i->tag eq 'script') { } 0 0 0
elsif ($i->tag eq 'form' and $base) { } 0 0 0
elsif ($i->tag eq 'a' || $i->tag eq 'area' || $i->tag eq 'link' and $i->attr('href') and not $i->attr('href') =~ /^\#/) { } 0 0 0
elsif ($i->tag eq 'td' and $i->attr('background') and $base) { } 0 0 0
Condition0%0/9
$i->tag eq "img" or $i->tag eq "frame" or $i->tag eq "input" or $i->tag eq "script"
l!l&&r!l&&!r
000
$i->tag eq "img" or $i->tag eq "frame" or $i->tag eq "input"
l!l&&r!l&&!r
000
$i->tag eq "img" or $i->tag eq "frame"
l!l&&r!l&&!r
000
MC/DC0%0/4
$i->tag eq "img" or $i->tag eq "frame" or $i->tag eq "input" or $i->tag eq "script"
$i->tag eq "img" $i->tag eq "frame" $i->tag eq "input" $i->tag eq "script"
Truth table0%0/5
A or B or C or D
A= $i->tag eq "img"B= $i->tag eq "frame"C= $i->tag eq "input"D= $i->tag eq "script"
ABCDresult
1XXX1
01XX1
001X1
00011
00000
702  
703 0 ▶ if ($i->attr('src') and $base) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i->attr("src") and $base) 0 0 0
Condition0%0/3
$i->attr("src") and $base
!ll&&!rl&&r
000
MC/DC0%0/2
$i->attr("src") and $base
$i->attr("src") $base
Truth table0%0/3
A and B
A= $i->attr("src")B= $base
ABresult
0X0
100
111
704 # Construct a uri object for the attribute 'src' value
705 0 my $uri = URI->new($i->attr('src'));
706 0 $i->attr('src',$uri->abs($base));
707 } # end 'src' attribute
708 }
709 ▶ elsif ($i->tag eq 'form' and $base) {
Condition0%0/3
$i->tag eq "form" and $base
!ll&&!rl&&r
000
MC/DC0%0/2
$i->tag eq "form" and $base
$i->tag eq "form" $base
Truth table0%0/3
A and B
A= $i->tag eq "form"B= $base
ABresult
0X0
100
111
710 # Construct a new uri for the 'action' attribute value
711 0 my $uri = URI->new($i->attr('action'));
712 0 $i->attr('action', $uri->abs($base));
713 }
714 ▶ elsif (($i->tag eq 'a' or $i->tag eq 'area' or $i->tag eq 'link') and $i->attr('href') and $i->attr('href') !~ /^\#/) {
Condition0%0/12
$i->tag eq "a" || $i->tag eq "area" || $i->tag eq "link" and $i->attr("href") and not $i->attr("href") =~ /^\#/
!ll&&!rl&&r
000
$i->tag eq "a" || $i->tag eq "area" || $i->tag eq "link" and $i->attr("href")
!ll&&!rl&&r
000
$i->tag eq "a" or $i->tag eq "area" or $i->tag eq "link"
l!l&&r!l&&!r
000
$i->tag eq "a" or $i->tag eq "area"
l!l&&r!l&&!r
000
MC/DC0%0/5
$i->tag eq "a" || $i->tag eq "area" || $i->tag eq "link" and $i->attr("href") and not $i->attr("href") =~ /^\#/
$i->tag eq "a" $i->tag eq "area" $i->tag eq "link" $i->attr("href") not $i->attr("href") =~ /^\#/
Truth table0%0/10
A or B or C and D and not(E)
A= $i->tag eq "a"B= $i->tag eq "area"C= $i->tag eq "link"D= $i->attr("href")E= not $i->attr("href") =~ /^\#/
ABCDEresult
000XX0
1XX0X0
01X0X0
0010X0
1XX100
01X100
001100
1XX111
01X111
001111
715 # Construct a new uri for the 'href' attribute value
716 0 my $uri = URI->new($i->attr('href'));
717  
718 # Expand URLs to absolute ones if base uri is defined.
719 0 ▶ my $newuri = $base ? $uri->abs($base) : $uri;
Branch: 1 branch
BranchTrueFalseTotal
$base ? : 0 0 0
720  
721 0 $i->attr('href', $newuri->as_string());
722 }
723 ▶ elsif ($i->tag eq 'td' and $i->attr('background') and $base) {
Condition0%0/6
$i->tag eq "td" and $i->attr("background") and $base
!ll&&!rl&&r
000
$i->tag eq "td" and $i->attr("background")
!ll&&!rl&&r
000
MC/DC0%0/3
$i->tag eq "td" and $i->attr("background") and $base
$i->tag eq "td" $i->attr("background") $base
Truth table0%0/4
A and B and C
A= $i->tag eq "td"B= $i->attr("background")C= $base
ABCresult
0XX0
10X0
1100
1111
724 # adjust 'td' background
725 0 my $uri = URI->new($i->attr('background'));
726 0 $i->attr('background',$uri->abs($base));
727 } # end tag choices
728  
729 # Recurse down tree
730 0 ▶ if (defined $i->content) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $i->content) 0 0 0
731 0 $self->__changelink_relative({ content => $i->content, baseref => $base });
732 }
733 }
734 }
735  
736 sub __fix_relative_url {
737 0 ▶ my ($self,$params) = @_;
Subroutine __fix_relative_url: not called CC=1 SCAR=6.9
738  
739 0 $self->_check_object();
740  
741 0 my $uri = URI->new($$params{url});
742  
743 0 return $$params{prefix} . "'" . $uri->abs($$params{base})->as_string ."'";
744 }
745  
746 sub __expand_stylesheet {
747 0 ▶ my ($self,$params) = @_;
Subroutine __expand_stylesheet: not called CC=10 SCAR=47.0
748  
749 0 $self->_check_object();
750  
751 0 my $doc = $$params{content};
752  
753 0 my $stylesheets = ();
754  
755 0 my (@style,@link);
756 0 ▶ if ($self->_relaxed()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_relaxed) { } 0 0 0
757 #get the <style> nodes
758 0 @style = $doc->look_down('_tag','style');
759  
760 #get the <link> nodes
761 0 @link = $doc->look_down('_tag','link','href',qr/./);
762 }
763 else {
764 #get the head section of the document
765 0 my $head = $doc->look_down('_tag', 'head'); # there should only be one
766  
767 #get the <style> nodes underneath the head section - that's the only place stylesheets are allowed to live
768 0 @style = $head->look_down('_tag','style');
769  
770 #get the <link> nodes underneath the head section - there should be *none* at this step in the process
771 0 @link = $head->look_down('_tag','link','href',qr/./);
772 }
773  
774 0 foreach my $i (@link) {
775 # determine attribute values for the link tag, assign some defaults to avoid comparison warnings later
776 0 ▶ my $rel = defined($i->attr('rel')) ? $i->attr('rel') : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $i->attr('rel') ? : 0 0 0
777 0 ▶ my $type = defined($i->attr('type')) ? $i->attr('type') : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $i->attr('type') ? : 0 0 0
778 0 ▶ my $href = defined($i->attr('href')) ? $i->attr('href') : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $i->attr('href') ? : 0 0 0
779  
780 # if we don't match the signature of an inlineable stylesheet, skip over
781 0 ▶ next unless (($rel eq 'stylesheet') || ($type eq 'text/css') || ($href =~ m/\.css$/));
Branch: 1 branch
BranchTrueFalseTotal
unless $rel eq "stylesheet" or $type eq "text/css" or $href =~ /\.css$/ 0 0 0
Condition0%0/6
$rel eq "stylesheet" or $type eq "text/css" or $href =~ /\.css$/
l!l&&r!l&&!r
000
$rel eq "stylesheet" or $type eq "text/css"
l!l&&r!l&&!r
000
MC/DC0%0/3
$rel eq "stylesheet" or $type eq "text/css" or $href =~ /\.css$/
$rel eq "stylesheet" $type eq "text/css" $href =~ /\.css$/
Truth table0%0/4
A or B or C
A= $rel eq "stylesheet"B= $type eq "text/css"C= $href =~ /\.css$/
ABCresult
1XX1
01X1
0011
0000
782  
783 0 my ($content,$baseref) = $self->_fetch_url({ url => $i->attr('href') });
784  
785 #absolutized the assetts within the stylesheet that are relative
786 0 $content =~ s/(url\()["']?((?:(?!https?:\/\/)(?!\))[^"'])*)["']?(?=\))/$self->__fix_relative_url({ prefix => $1, url => $2, base => $baseref })/exsgi;
787  
788 0 my $stylesheet = HTML::Element->new('style', type => 'text/css', rel=> 'stylesheet');
789 0 $stylesheet->push_content($content);
790  
791 0 $i->replace_with($stylesheet);
792 }
793  
794 0 foreach my $i (@style) {
795 #use the baseref from the original document fetch
796 0 my $baseref = $$params{html_baseref};
797  
798 0 my @content = $i->content_list();
799 0 my $content = join('',grep {! ref $_ } @content);
800  
801 # absolutize the assets within the stylesheet that are relative
802 0 $content =~ s/(url\()["']?((?:(?!https?:\/\/)(?!\))[^"'])*)["']?(?=\))/$self->__fix_relative_url({ prefix => $1, url => $2, base => $baseref })/exsgi;
803  
804 0 my $stylesheet = HTML::Element->new('style', type => 'text/css', rel=> 'stylesheet');
805 0 $stylesheet->push_content($content);
806  
807 0 $i->replace_with($stylesheet);
808 }
809  
810 0 return();
811 }
812  
813 sub _validate_html {
814 27 ▶ my ($self,$params) = @_;
Subroutine _validate_html: called CC=18 SCAR=43.5
815  
816 27 my $validator_tree = new CSS::Inliner::TreeBuilder();
817  
818 27 $validator_tree->ignore_unknown(0);
819 27 $validator_tree->implicit_tags(0);
820 27 $validator_tree->parse_content($$params{html});
821  
822 27 ▶ if ($self->_relaxed()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_relaxed) { } 1 26 27
823 # TODO: print out any html issues that would cause the relaxed parsing to modify the document or might cause
824 # a rendering problem of some type
825 #
826 # Currently there are no known issues, but when found they would go here
827 }
828 else {
829 # The following are inconsistencies that can easily be found by scanning our document using the internal Treebuilder
830 # The standard TreeBuilder actually alters the document in an attempt to create something "valid", but by doing so
831 # all sorts of weird things can happen, so we add them to the warnings report so the caller knows what's going on.
832  
833 # count up the major structural components of the document
834 26 my @html_nodes = $validator_tree->look_down('_tag', 'html');
835 26 my @head_nodes = $validator_tree->look_down('_tag', 'head');
836 26 my @body_nodes = $validator_tree->look_down('_tag', 'body');
837  
838 # we should have exactly 2 root nodes, the treebuilder inserted one and the nested one from the document...
839 26 ▶ if (scalar @html_nodes == 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (scalar @html_nodes == 0) { } 1 25 26
elsif (scalar @html_nodes > 1) { } 0 25 25
840 1 $self->_report_warning({ info => 'Unexpected absence of html root node, force inserted' });
841 }
842 elsif (scalar @html_nodes > 1) {
843 0 $self->_report_warning({ info => 'Unexpected spurious html root node(s) found within referenced document, coalesced' });
844 }
845  
846 26 ▶ if (scalar @head_nodes > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @head_nodes > 1) 0 26 26
847 0 $self->_report_warning({ info => 'Unexpected spurious head node(s) found within referenced document, coalesced' });
848 }
849  
850 26 ▶ if (scalar @body_nodes > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @body_nodes > 1) 0 26 26
851 0 $self->_report_warning({ info => 'Unexpected spurious body node(s) found within referenced document, coalesced' });
852 }
853  
854 26 my @link = $validator_tree->look_down('_tag','link','href',qr/./);
855  
856 26 foreach my $i (@link) {
857 0 ▶ my $rel = defined($i->attr('rel')) && $i->attr('rel') ? $i->attr('rel') : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $i->attr('rel') && $i->attr('rel') ? : 0 0 0
Condition0%0/3
defined $i->attr("rel") and $i->attr("rel")
!ll&&!rl&&r
000
MC/DC0%0/2
defined $i->attr("rel") and $i->attr("rel")
defined $i->attr("rel") $i->attr("rel")
Truth table0%0/3
A and B
A= defined $i->attr("rel")B= $i->attr("rel")
ABresult
0X0
100
111
858 0 ▶ my $type = defined($i->attr('type')) && $i->attr('type') ? $i->attr('type') : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $i->attr('type') && $i->attr('type') ? : 0 0 0
Condition0%0/3
defined $i->attr("type") and $i->attr("type")
!ll&&!rl&&r
000
MC/DC0%0/2
defined $i->attr("type") and $i->attr("type")
defined $i->attr("type") $i->attr("type")
Truth table0%0/3
A and B
A= defined $i->attr("type")B= $i->attr("type")
ABresult
0X0
100
111
859 0 ▶ my $href = defined($i->attr('href')) && $i->attr('href') ? $i->attr('href') : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $i->attr('href') && $i->attr('href') ? : 0 0 0
Condition0%0/3
defined $i->attr("href") and $i->attr("href")
!ll&&!rl&&r
000
MC/DC0%0/2
defined $i->attr("href") and $i->attr("href")
defined $i->attr("href") $i->attr("href")
Truth table0%0/3
A and B
A= defined $i->attr("href")B= $i->attr("href")
ABresult
0X0
100
111
860  
861 # link references to stylesheets at this point in the workflow means the caller is doing something improper
862 # currently such references are only chased down if you fetch a document, not if you feed one in
863 0 ▶ if ($rel eq 'stylesheet' || $type eq 'text/css' || $href =~ m/.css$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rel eq "stylesheet" or $type eq "text/css" or $href =~ /.css$/) 0 0 0
Condition0%0/6
$rel eq "stylesheet" or $type eq "text/css" or $href =~ /.css$/
l!l&&r!l&&!r
000
$rel eq "stylesheet" or $type eq "text/css"
l!l&&r!l&&!r
000
MC/DC0%0/3
$rel eq "stylesheet" or $type eq "text/css" or $href =~ /.css$/
$rel eq "stylesheet" $type eq "text/css" $href =~ /.css$/
Truth table0%0/4
A or B or C
A= $rel eq "stylesheet"B= $type eq "text/css"C= $href =~ /.css$/
ABCresult
1XX1
01X1
0011
0000
864 0 $self->_report_warning({ info => 'Unexpected reference to remote stylesheet was not inlined' });
865 0 last;
866 }
867 }
868  
869 26 my $body = $self->_html_tree->look_down('_tag', 'body');
870  
871 26 ▶ if ($body) {
Branch: 1 branch
BranchTrueFalseTotal
if ($body) 26 0 26
872 # located spurious <style> tags that won't be handled
873 26 my @spurious_style = $body->look_down('_tag','style','type','text/css');
874  
875 26 ▶ if (scalar @spurious_style) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @spurious_style) 0 26 26
876 0 $self->_report_warning({ info => 'Unexpected reference to stylesheet within document body skipped' });
877 }
878 }
879 }
880  
881 27 return();
882 }
883  
884 sub _parse_stylesheet {
885 27 ▶ my ($self,$params) = @_;
Subroutine _parse_stylesheet: called CC=8 SCAR=20.9
886  
887 27 $self->_check_object();
888  
889 27 my $stylesheet = '';
890  
891 # figure out where to look for styles
892 27 ▶ my $stylesheet_root = $self->_relaxed() ? $self->_html_tree() : $self->_html_tree->look_down('_tag', 'head');
Branch: 1 branch
BranchTrueFalseTotal
$self->_relaxed ? : 1 26 27
893  
894 # get the <style> nodes
895 27 my @style = $stylesheet_root->look_down('_tag','style','type','text/css');
896  
897 27 foreach my $i (@style) {
898 #process this node if the html media type is screen, all or undefined (which defaults to screen)
899 27 ▶ if (($i->tag eq 'style') && (!$i->attr('media') || $i->attr('media') =~ m/\b(all|screen)\b/)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i->tag eq "style" and !$i->attr("media") || $i->attr("media") =~ /\b(all|screen)\b/) 27 0 27
Condition66%4/6
$i->tag eq "style" and !$i->attr("media") || $i->attr("media") =~ /\b(all|screen)\b/
!ll&&!rl&&r
0252
not $i->attr("media") or $i->attr("media") =~ /\b(all|screen)\b/
l!l&&r!l&&!r
2520
MC/DC0%0/3
$i->tag eq "style" and !$i->attr("media") || $i->attr("media") =~ /\b(all|screen)\b/
$i->tag eq "style" not $i->attr("media") $i->attr("media") =~ /\b(all|screen)\b/
Truth table25%1/4
A and not(B) or C
A= $i->tag eq "style"B= not $i->attr("media")C= $i->attr("media") =~ /\b(all|screen)\b/
ABCresult
0XX0
1000
11X1
1011
900  
901 27 foreach my $item ($i->content_list()) {
902 # remove HTML comment markers
903 27 $item =~ s/<!--//mg;
904 27 $item =~ s/-->//mg;
905  
906 27 $stylesheet .= $item;
907 }
908 }
909  
910 27 ▶ unless ($self->_leave_style()) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_leave_style) 24 3 27
911 24 $i->delete();
912 }
913 }
914  
915 27 return $stylesheet;
916 }
917  
918 sub _collapse_inline_styles {
919 378 ▶ my ($self,$params) = @_;
Subroutine _collapse_inline_styles: called CC=9 SCAR=22.0
920  
921 378 $self->_check_object();
922  
923 #check if we were passed a node to recurse from, otherwise use the root of the tree
924 378 ▶ my $content = exists($$params{content}) ? $$params{content} : [$self->_html_tree()];
Branch: 1 branch
BranchTrueFalseTotal
exists $params->{'content'} ? : 351 27 378
925  
926 378 foreach my $i (@{$content}) {
927  
928 639 ▶ next unless (ref $i && $i->isa('HTML::Element'));
Branch: 1 branch
BranchTrueFalseTotal
unless ref $i and $i->isa("HTML::Element") 259 380 639
Condition66%2/3
ref $i and $i->isa("HTML::Element")
!ll&&!rl&&r
2590380
MC/DC50%1/2
ref $i and $i->isa("HTML::Element")
ref $i $i->isa("HTML::Element")
Truth table66%2/3
A and B
A= ref $iB= $i->isa("HTML::Element")
ABresult
0X0
100
111
929  
930 380 ▶ if ($i->attr('style')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i->attr("style")) 174 206 380
931  
932 #flatten out the styles currently in place on this entity
933 174 my $existing_styles = $i->attr('style');
934 174 $existing_styles =~ tr/\n\t/ /;
935  
936 # hold the property value pairs
937 174 my $styles = $self->_split({ style => $existing_styles });
938  
939 174 my $collapsed_style = '';
940 174 foreach my $key (sort keys %{$styles}) { #sort for predictable output
941 415 $collapsed_style .= $key . ': ' . $$styles{$key} . '; ';
942 }
943  
944 174 $collapsed_style =~ s/\s*$//;
945 174 $i->attr('style', $collapsed_style);
946 }
947  
948 #if we have specifically asked to remove the inlined attrs, remove them
949 380 ▶ if ($self->_strip_attrs()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_strip_attrs) 17 363 380
950 17 $i->attr('id',undef);
951 17 $i->attr('class',undef);
952 }
953  
954 # Recurse down tree
955 380 ▶ if (defined $i->content) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $i->content) 351 29 380
956 351 $self->_collapse_inline_styles({ content => $i->content() });
957 }
958 }
959 }
960  
961 sub _extract_meta_charset {
962 0 ▶ my ($self,$params) = @_;
Subroutine _extract_meta_charset: not called CC=6 SCAR=37.4
963  
964 0 $self->_check_object();
965  
966 # we are going to parse an html document as ascii that is not necessarily ascii - silence the warning
967 0 ▶ local $SIG{__WARN__} = sub { my $warning = shift; warn $warning unless $warning =~ /^Parsing of undecoded UTF-8/ };
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
unless $warning =~ /^Parsing of undecoded UTF-8/ 0 0 0
968  
969 # parse document and pull out key header elements
970 0 my $extract_tree = new CSS::Inliner::TreeBuilder();
971 0 $self->_configure_tree({ tree => $extract_tree });
972  
973 0 $extract_tree->parse_content($$params{content});
974  
975 0 my $head = $extract_tree->look_down("_tag", "head"); # there should only be one
976  
977 0 my $meta_charset;
978 0 ▶ if ($head) {
Branch: 1 branch
BranchTrueFalseTotal
if ($head) 0 0 0
979 # pull key header meta elements
980 0 my $meta_charset_elem = $head->look_down('_tag','meta','charset',qr/./);
981 0 my $meta_equiv_charset_elem = $head->look_down('_tag','meta','http-equiv',qr/content-type/i,'content',qr/./);
982  
983 # assign meta charset, we give precedence to meta http_equiv content type
984 0 ▶ if ($meta_equiv_charset_elem) {
Branch: 1 branch
BranchTrueFalseTotal
if ($meta_equiv_charset_elem) 0 0 0
985 0 my $meta_equiv_content = $meta_equiv_charset_elem->attr('content');
986  
987 # leverage charset allowable chars from https://tools.ietf.org/html/rfc2978
988 0 ▶ if ($meta_equiv_content =~ /charset(?:\s*)=(?:\s*)([\w!#$%&'\-+^`{}~]+)/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($meta_equiv_content =~ /charset(?:\s*)=(?:\s*)([\w!#$%&'\-+^`{}~]+)/i) 0 0 0
989 0 $meta_charset = find_encoding($1);
990 }
991 }
992  
993 0 ▶ if (!defined($meta_charset) && $meta_charset_elem) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $meta_charset and $meta_charset_elem) 0 0 0
Condition0%0/3
not defined $meta_charset and $meta_charset_elem
!ll&&!rl&&r
000
MC/DC0%0/2
not defined $meta_charset and $meta_charset_elem
not defined $meta_charset $meta_charset_elem
Truth table0%0/3
not(A) and B
A= not defined $meta_charsetB= $meta_charset_elem
ABresult
0X0
100
111
994 0 $meta_charset = find_encoding($meta_charset_elem->attr('charset'));
995 }
996 }
997  
998 0 return $meta_charset;
999 }
1000  
1001 sub _init_query {
1002 28 ▶ my ($self,$params) = @_;
Subroutine _init_query: called CC=1 SCAR=0.0
1003  
1004 28 $self->_check_object();
1005  
1006 28 $self->{query} = HTML::Query->new($self->_html_tree());
1007  
1008 28 return();
1009 }
1010  
1011 sub _expand {
1012 173 ▶ my ($self, $params) = @_;
Subroutine _expand: called CC=2 SCAR=6.9
1013  
1014 173 $self->_check_object();
1015  
1016 173 my $declarations = $$params{declarations};
1017 173 my $inline = '';
1018 173 foreach my $property (keys %{$declarations}) {
1019 413 $inline .= $property . ':' . $$declarations{$property} . ';';
1020 }
1021  
1022 173 return $inline;
1023 }
1024  
1025 sub _split {
1026 182 ▶ my ($self, $params) = @_;
Subroutine _split: called CC=3 SCAR=11.1
1027  
1028 182 $self->_check_object();
1029  
1030 182 my $style = $params->{style};
1031 182 my %split;
1032  
1033 # Split into properties/values
1034 182 foreach ( grep { /\S/ } split /\;/, $style ) {
1035 426 ▶ unless ( /^\s*([\w._-]+)\s*:\s*(.*?)\s*$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (/^\s*([\w._-]+)\s*:\s*(.*?)\s*$/) 0 426 426
1036 0 $self->_report_warning({ info => "Invalid or unexpected property '$_' in style '$style'" });
1037 }
1038 426 $split{lc $1} = $2;
1039 }
1040  
1041 182 return \%split;
1042 }
1043  
1044 sub _grep_important_declarations {
1045 283 ▶ my ($declarations) = @_;
Subroutine _grep_important_declarations: called CC=3 SCAR=11.0
1046  
1047 283 my %important;
1048  
1049 283 ▶ while (my ($property, $value) = each %$declarations) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %$declarations) 466 283 749
1050 466 ▶ if ($value =~ /!\s*important\s*$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($value =~ /!\s*important\s*$/i) 1 465 466
1051 1 $important{$property} = $value;
1052 }
1053 }
1054  
1055 283 return %important;
1056 }
1057  
1058 26 1;
1059  
1060 =head1 AUTHOR
1061  
1062 Kevin Kamel <kamelkev@underprint.com>
1063  
1064 =head1 CONTRIBUTORS
1065  
1066 Dave Gray <cpan@doesntsuck.com>
1067 Vivek Khera <vivek@khera.org>
1068 Michael Peters <wonko@cpan.org>
1069 Chelsea Rio <chelseario@gmail.com>
1070  
1071 =head1 LICENSE
1072  
1073 This module is Copyright 2017 Khera Communications, Inc. It is
1074 licensed under the same terms as Perl itself.
1075  
1076 =cut
↑ Summary blib/lib/CSS/Inliner.pm »