lib/Serge/Engine/Plugin/parse_xml.pm

filter: Statementstmt 32.3% 22 / 68 Branchbran 0.0% 0 / 18 Conditioncond 0.0% 0 / 8 MC/DCmcdc 0.0% 0 / 5 Subroutinesub 66.6% 8 / 12 Podpod n/a totaltotal 27.0% 30 / 111 SCAR 46.3
CC
14
Cov
23%
report_errors
156.0
validate_data
12.0
name
2.0
CRAP 102.1
« lib/Serge/Engine/Plugin/parse_chrome_json.pm ↑ Summary lib/Serge/Engine/Plugin/Transform/wrappertag.pm »
1 package Serge::Engine::Plugin::parse_xml;
2 1 ▶use parent Serge::Engine::Plugin::Base::Parser;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 1 ▶use parent Serge::Interface::PluginHost;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 1 ▶no warnings qw(uninitialized);
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 1 ▶use File::Path;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use Serge::Mail;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use Serge::Util qw(xml_escape_strref xml_unescape_strref);
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 sub name {
14 0 ▶ return 'Generic XML parser plugin';
Subroutine name: not called CC=1 SCAR=6.9
15 }
16  
17 sub init {
18 0 ▶ my $self = shift;
Subroutine init: not called CC=1 SCAR=6.9
19  
20 0 $self->SUPER::init(@_);
21  
22 0 $self->{errors} = {};
23  
24 0 $self->merge_schema({
25 node_match => 'ARRAY',
26 node_exclude => 'ARRAY',
27 node_html => 'ARRAY',
28 xml_kind => 'STRING',
29  
30 email_from => 'STRING',
31 email_to => 'ARRAY',
32 email_subject => 'STRING',
33  
34 html_parser => {
35 plugin => 'STRING',
36  
37 data => {
38 '*' => 'DATA',
39 }
40 },
41 });
42  
43 0 $self->add('after_job', \&report_errors);
44 }
45  
46 sub validate_data {
47 0 ▶ my $self = shift;
Subroutine validate_data: not called CC=3 SCAR=24.8
48  
49 0 $self->SUPER::validate_data;
50  
51 0 ▶ if (exists $self->{data}->{xml_kind} && ($self->{data}->{xml_kind} !~ m/^(generic|android|indesign)$/)) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $self->{"data"}{"xml_kind"} and not $self->{"data"}{"xml_kind"} =~ /^(generic|android|indesign)$/) 0 0 0
Condition0%0/3
exists $self->{"data"}{"xml_kind"} and not $self->{"data"}{"xml_kind"} =~ /^(generic|android|indesign)$/
!ll&&!rl&&r
000
MC/DC0%0/2
exists $self->{"data"}{"xml_kind"} and not $self->{"data"}{"xml_kind"} =~ /^(generic|android|indesign)$/
exists $self->{"data"}{"xml_kind"} not $self->{"data"}{"xml_kind"} =~ /^(generic|android|indesign)$/
Truth table0%0/3
A and not(B)
A= exists $self->{"data"}{"xml_kind"}B= not $self->{"data"}{"xml_kind"} =~ /^(generic|android|indesign)$/
ABresult
0X0
100
111
52 0 die "Unsupported xml_kind: '$self->{data}->{xml_kind}'. You can use 'generic' (default), 'android' or 'indesign'";
53 }
54  
55 0 $self->{data}->{xml_kind_android} = ($self->{data}->{xml_kind} eq 'android');
56 0 $self->{data}->{xml_kind_indesign} = ($self->{data}->{xml_kind} eq 'indesign');
57 }
58  
59 sub report_errors {
60 0 ▶ my ($self, $phase) = @_;
Subroutine report_errors: not called CC=12 SCAR=50.5
61  
62 # copy over errors from the child parser, if any
63 0 ▶ if ($self->{html_parser}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"html_parser"}) 0 0 0
64 0 my @keys = keys %{$self->{html_parser}->{errors}};
65 0 ▶ if (scalar @keys > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @keys > 0) 0 0 0
66 map {
67 0 $self->{errors}->{$_} = $self->{html_parser}->{errors}->{$_};
68 } @keys;
69 0 $self->{html_parser}->{errors} = {};
70 }
71 }
72  
73 0 ▶ return if !scalar keys %{$self->{errors}};
Branch: 1 branch
BranchTrueFalseTotal
unless scalar keys %{$$self{"errors"};} 0 0 0
74  
75 0 my $email_from = $self->{data}->{email_from};
76 0 my $email_to = $self->{data}->{email_to};
77  
78 0 ▶ if (!$email_from || !$email_to) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($email_from and $email_to) 0 0 0
Condition0%0/3
$email_from and $email_to
!ll&&!rl&&r
000
MC/DC0%0/2
$email_from and $email_to
$email_from $email_to
Truth table0%0/3
A and B
A= $email_fromB= $email_to
ABresult
0X0
100
111
79 0 my @a;
80 0 ▶ push @a, "'email_from'" unless $email_from;
Branch: 1 branch
BranchTrueFalseTotal
unless $email_from 0 0 0
81 0 ▶ push @a, "'email_to'" unless $email_to;
Branch: 1 branch
BranchTrueFalseTotal
unless $email_to 0 0 0
82 0 my $fields = join(' and ', @a);
83 0 ▶ my $are = scalar @a > 1 ? 'are' : 'is';
Branch: 1 branch
BranchTrueFalseTotal
scalar @a > 1 ? : 0 0 0
84 0 print "WARNING: there are some parsing errors, but $fields $are not defined, so can't send an email.\n";
85 0 $self->{errors} = {};
86 0 return;
87 }
88  
89 0 ▶ my $email_subject = $self->{data}->{email_subject} || ("[".$self->{parent}->{id}.']: XML Parse Errors');
Condition0%0/2
$self->{'data'}{'email_subject'} || '[' . $self->{'parent'}{'id'} . ']: XML Parse Errors'
l!l
00
MC/DC0%0/1
$self->{'data'}{'email_subject'} || '[' . $self->{'parent'}{'id'} . ']: XML Parse Errors'
$self->{'data'}{'email_subject'}
Truth table0%0/2
A
A= $self->{'data'}{'email_subject'}
Aresult
11
00
90  
91 0 my $text;
92 0 foreach my $key (sort keys %{$self->{errors}}) {
93 0 my $pre_contents = $self->{errors}->{$key};
94 0 xml_escape_strref(\$pre_contents);
95 0 $text .= "<hr />\n<p><b style='color: red'>$key</b> <pre>".$pre_contents."</pre></p>\n";
96 }
97  
98 0 $self->{errors} = {};
99  
100 0 ▶ if ($text) {
Branch: 1 branch
BranchTrueFalseTotal
if ($text) 0 0 0
101 0 $text = qq|
102 <html>
103 <head>
104 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
105 </head>
106 <body style="font-family: sans-serif; font-size: 120%">
107  
108 <p>
109 # This is an automatically generated message.
110  
111 The following parsing errors were found when attempting to localize resource files.
112 </p>
113  
114 $text
115  
116 </body>
117 </html>
118 |;
119  
120 0 Serge::Mail::send_html_message(
121 $email_from, # from
122 $email_to, # to (list)
123 $email_subject, # subject
124 $text # message body
125 );
126 }
127  
128 }
129  
130 sub parse {
131 my ($self, $textref, $callbackref, $lang) = @_;
132  
133 die 'callbackref not specified' unless $callbackref;
134  
135 die 'node_match not specified' unless $self->{data}->{node_match};
136  
137 my $node_match = $self->{data}->{node_match} || [];
138 my $node_exclude = $self->{data}->{node_exclude} || [];
139 my $node_html = $self->{data}->{node_html} || [];
140  
141 # Make a copy of the string as we will change it
142  
143 my $text = $$textref;
144  
145 # Replace the symbolic entities as we are not going to expand them
146  
147 $text =~ s/&(\w+);/'__HTML__ENTITY__'.$1.'__'/ge;
148  
149 # Wrap CDATA blocks inside special '__CDATA' tag
150 # to be able to reconstruct it later
151  
152 $text =~ s/(<\!\[CDATA\[.*?\]\]>)/'<__CDATA>'._escape_pi_and_comments($1).'<\/__CDATA>'/sge;
153  
154 # Wrap processing instruction inside special '__PI' tag
155 # to be able to reconstruct it later
156  
157 $text =~ s/<\?(.*?)\?>/<__PI><\!\[CDATA\[$1\]\]><\/__PI>/sg;
158  
159 # Wrap HTML comment inside special '__COMMENT' tag
160 # to be able to reconstruct it later
161  
162 $text =~ s/<\!--(.*?)-->/<__COMMENT><\!\[CDATA\[$1\]\]><\/__COMMENT>/sg;
163  
164 # Restore escaped processing instructions and comments inside cdata
165  
166 $text = _unescape_pi_and_comments($text);
167  
168 # Add the dummy root tag for XML to be valid
169  
170 $text = '<__ROOT>'.$text.'</__ROOT>';
171  
172 # Create XML parser object
173  
174 1 ▶ use XML::Parser;
Subroutine BEGIN: called CC=1 SCAR=2.6
175 my $parser = new XML::Parser(Style => 'IxTree');
176  
177 # Parse XML
178  
179 my $tree;
180 eval {
181 $tree = $parser->parse($text);
182 };
183 if ($@) {
184 my $error_text = $@;
185 $error_text =~ s/\t/ /g;
186 $error_text =~ s/^\s+//s;
187  
188 $self->{errors}->{$self->{parent}->{engine}->{current_file_rel}} = $error_text;
189  
190 die $error_text;
191 }
192  
193 # Add the empty attributes hash to the root tag (for uniform processing)
194  
195 unshift @$tree, {};
196  
197 # Process tree recursively and generate the localized output
198  
199 my $out = $self->render_tag_recursively('', $tree, $callbackref, $lang, '');
200  
201 return $lang ? $out : undef;
202 }
203  
204 sub _escape_pi_and_comments {
205 my $text = shift;
206  
207 $text =~ s/<\?/__PI_START__/sg;
208 $text =~ s/\?>/__PI_END__/sg;
209 $text =~ s/<\!--/__COMMENT_START__/sg;
210 $text =~ s/-->/__COMMENT_END__/sg;
211  
212 return $text;
213 }
214  
215 sub _unescape_pi_and_comments {
216 my $text = shift;
217  
218 $text =~ s/__PI_START__/<\?/sg;
219 $text =~ s/__PI_END__/\?>/sg;
220 $text =~ s/__COMMENT_START__/<\!--/sg;
221 $text =~ s/__COMMENT_END__/-->/sg;
222  
223 return $text;
224 }
225  
226 sub process_text_node {
227 my ($self, $path, $attrs, $strref, $callbackref, $lang, $cdata, $noquotes) = @_;
228  
229 # Check if node path matches our expectations
230  
231 my $ok = undef;
232  
233 # Test if node path matches the mask
234  
235 foreach my $rule (@{$self->{data}->{node_match}}) {
236 if (ref($rule) eq "HASH") {
237 my $prule = $rule->{path};
238 if ($path =~ m/$prule/) {
239 my $attrs_ok = 1;
240 foreach my $name (keys %{$rule->{attributes}}) {
241 my $arule = $rule->{attributes}->{$name};
242 if ($attrs->{$name} !~ m/$arule/) {
243 print "\t\t\tattribute '$name' [".$attrs->{$name}."] doesn't match rule '$arule'\n" if $self->{parent}->{debug};
244 $attrs_ok = undef;
245 last;
246 }
247 }
248 if ($attrs_ok) {
249 $ok = 1;
250 last;
251 }
252 } else {
253 print "\t\t\tpath doesn't match\n" if $self->{parent}->{debug};
254 }
255 } else { # treat rule as a string
256 if ($path =~ m/$rule/) {
257 $ok = 1;
258 last;
259 }
260 }
261 }
262  
263 # Test if node path does not match the exclusion mask
264  
265 if ($ok) {
266 foreach my $rule (@{$self->{data}->{node_exclude}}) {
267 if (ref($rule) eq "HASH") {
268 my $prule = $rule->{path};
269 if ($path =~ m/$prule/) {
270 my $attrs_ok = 1;
271 foreach my $name (keys %{$rule->{attributes}}) {
272 my $arule = $rule->{attributes}->{$name};
273 if ($attrs->{$name} !~ m/$arule/) {
274 print "\t\t\t[exclude] attribute '$name' [".$attrs->{$name}."] doesn't match rule '$arule'\n" if $self->{parent}->{debug};
275 $attrs_ok = undef;
276 last;
277 }
278 }
279 if ($attrs_ok) {
280 $ok = undef;
281 last;
282 }
283 } else {
284 print "\t\t\t[exclude] path doesn't match\n" if $self->{parent}->{debug};
285 }
286 } else { # treat rule as a string
287 if ($path =~ m/$rule/) {
288 $ok = undef;
289 last;
290 }
291 }
292 }
293 }
294  
295 # Test if node path matches the html mask
296  
297 my $is_html = undef;
298  
299 if ($ok) {
300 foreach my $rule (@{$self->{data}->{node_html}}) {
301 if (ref($rule) eq "HASH") {
302 my $prule = $rule->{path};
303 if ($path =~ m/$prule/) {
304 my $attrs_ok = 1;
305 foreach my $name (keys %{$rule->{attributes}}) {
306 my $arule = $rule->{attributes}->{$name};
307 if ($attrs->{$name} !~ m/$arule/) {
308 print "\t\t\tattribute '$name' [".$attrs->{$name}."] doesn't match rule '$arule'\n" if $self->{parent}->{debug};
309 $attrs_ok = undef;
310 last;
311 }
312 }
313 if ($attrs_ok) {
314 $is_html = 1;
315 last;
316 }
317 } else {
318 print "\t\t\tpath doesn't match\n" if $self->{parent}->{debug};
319 }
320 } else { # treat rule as a string
321 if ($path =~ m/$rule/) {
322 $is_html = 1;
323 last;
324 }
325 }
326 }
327 }
328  
329 if ($self->{parent}->{debug}) {
330 if ($ok) {
331 if ($is_html) {
332 print "\t\t[ok, HTML mode] $path\n";
333 } else {
334 print "\t\t[ok] $path\n";
335 }
336 } else {
337 print "\t\t[--] $path\n";
338 }
339 }
340  
341 # reconstruct original XML with symbolic entities
342 # (do this before we exit to make sure all text nodes, even those
343 # not matching the mask, will be restored)
344 $$strref =~ s/__HTML__ENTITY__(\w+?)__/&$1;/g;
345  
346 # now exit if the node doesn't match the mask
347 return unless $ok;
348  
349 # in InDesign mode, strip the line break Unicode symbols since these are generally English-specific
350 # (? need to verify ?)
351 if ($self->{data}->{xml_kind_indesign}) {
352 $$strref =~ s/\x{2028}//g; # Unicode Character 'LINE SEPARATOR' (U+2028)
353 }
354  
355 # trim the string
356 my $trimmed = $$strref;
357  
358 $trimmed =~ s/^\s+//sg;
359 $trimmed =~ s/\s+$//sg;
360  
361 # 1) skip empty strings
362 # 2) skip strings consisting of non-alphabet characters (bullets, arrows, etc.)
363 # 3) skip strings representing plain numbers
364 if ($trimmed ne '' && $trimmed !~ m/^(\W+|\d+)$/) {
365 # in InDesign mode, preserve the leading and trailing whitespace
366 my ($leading_whitespace, $trailing_whitespace);
367 if ($self->{data}->{xml_kind_indesign}) {
368 ($$strref =~ m/^(\s+)/) && ($leading_whitespace = $1);
369 ($$strref =~ m/(\s+)$/) && ($trailing_whitespace = $1);
370 }
371  
372 $$strref = $trimmed;
373  
374 # unescape basic XML entities unless we're inside CDATA block
375 xml_unescape_strref($strref) unless $cdata;
376  
377 if ($is_html) {
378 # if node is html, pass its text to html parser for string extraction
379 # if html_parser fails to parse the XML due to errors,
380 # it will die(), and this will be catched in main application
381  
382 # lazy-load html parser plugin
383 # (parse_php_xhtml or the one specified in html_parser config node)
384 if (!$self->{html_parser}) {
385 if (exists $self->{data}->{html_parser}) {
386 $self->{html_parser} = $self->load_plugin_from_node(
387 'Serge::Engine::Plugin', $self->{data}->{html_parser}
388 );
389 } else {
390 # fallback to loading parse_php_xhtml with default parameters
391 eval('use Serge::Engine::Plugin::parse_php_xhtml; $self->{html_parser} = Serge::Engine::Plugin::parse_php_xhtml->new($self->{parent});');
392 ($@) && die "Can't load parser plugin 'parse_php_xhtml': $@";
393 print "Loaded HTML parser plugin for HTML nodes\n" if $self->{parent}->{debug};
394 }
395 }
396  
397 $self->{html_parser}->{current_file_rel} = $self->{parent}->{engine}->{current_file_rel}.":$path";
398 if ($lang) {
399 $$strref = $self->{html_parser}->parse($strref, $callbackref, $lang);
400 if (defined $$strref) {
401 # escape unsafe xml chars unless we're in CDATA block
402 xml_escape_strref($strref, $noquotes) unless $cdata;
403 } else {
404 $$strref = $trimmed;
405 }
406 } else {
407 $self->{html_parser}->parse($strref, $callbackref);
408 }
409 } else {
410 # additionally unescape Android-specific stuff, if requested
411 _android_unescape($strref) if ($self->{data}->{xml_kind_android});
412  
413 if ($lang) {
414 $$strref = &$callbackref($$strref, undef, $path, undef, $lang);
415 } else {
416 &$callbackref($$strref, undef, $path, undef, undef);
417 }
418  
419 # escape Android-specific stuff if requested
420 _android_escape($strref) if ($self->{data}->{xml_kind_android});
421  
422 # preserve symbolic entities from escaping
423 $$strref =~ s/&(\w+);/'__HTML__ENTITY__'.$1.'__'/ge;
424  
425 # escape unsafe xml chars (in Android mode, do not xml-escape quotes)
426 $noquotes = $noquotes || $self->{data}->{xml_kind_android};
427 xml_escape_strref($strref, $noquotes) unless $cdata;
428  
429 # restore symbolic entities
430 $$strref =~ s/__HTML__ENTITY__(\w+?)__/&$1;/g;
431  
432 # in InDesign mode, make sure the leading and trailing whitespace
433 # is restored to the original values
434 if ($self->{data}->{xml_kind_indesign}) {
435 $$strref =~ s/^(\s+)/$leading_whitespace/e;
436 $$strref =~ s/(\s+)$/$trailing_whitespace/e;
437 }
438 }
439 }
440 }
441  
442 sub _android_unescape {
443 my ($strref) = @_;
444  
445 $$strref =~ s/\\'/'/g; # Android-specific apostrophe unescaping
446 $$strref =~ s/\\"/"/g; # Android-specific quote unescaping
447 }
448  
449 sub _android_escape {
450 my ($strref) = @_;
451  
452 $$strref =~ s/'/\\'/g; # Android-specific apostrophe escaping
453 $$strref =~ s/"/\\"/g; # Android-specific quote escaping
454  
455 }
456  
457 sub _dummy_callback {
458 my ($s) = @_;
459 return $s;
460 }
461  
462 sub render_tag_recursively {
463 my ($self, $name, $subtree, $callbackref, $lang, $path, $cdata, $parent_attrs) = @_;
464 my $attrs = $subtree->[0];
465  
466 $cdata = 1 if (($name eq '__CDATA') || ($name eq '__COMMENT') || ($name eq '__PI'));
467  
468 my $inner_xml = '';
469  
470 for (my $i = 0; $i < (scalar(@$subtree) - 1) / 2; $i++) {
471 my $tagname = $subtree->[1 + $i*2];
472 my $tagtree = $subtree->[1 + $i*2 + 1];
473  
474 # do not process text inside processing instructions
475 # TODO: this can potentially be a conditional option, disabled by default
476 if ($tagname eq '__PI') {
477 $inner_xml .= $self->render_tag_recursively($tagname, $tagtree, \&_dummy_callback, $lang, $path, $cdata, $attrs);
478 next;
479 }
480  
481 if ($tagname ne '0') {
482 # node does not contain plain text, render the subtree
483  
484 my $tagpath;
485 if (($tagname eq '__ROOT') || ($tagname eq '__CDATA') || ($tagname eq '__COMMENT') || ($tagname eq '__PI')) {
486 $tagpath = $path;
487 } else {
488 $tagpath = $path.'/'.$tagname;
489 }
490  
491 if ($lang) {
492 $inner_xml .= $self->render_tag_recursively($tagname, $tagtree, $callbackref, $lang, $tagpath, $cdata, $attrs);
493 } else {
494 $self->render_tag_recursively($tagname, $tagtree, $callbackref, $lang, $tagpath, $cdata, $attrs);
495 }
496 } else {
497 # tagtree holds a string for text nodes
498  
499 my $str = $tagtree;
500  
501 $self->process_text_node($path, $parent_attrs, \$str, $callbackref, $lang, $cdata, 1);
502  
503 if ($lang) {
504 $inner_xml .= $str;
505 }
506 }
507 }
508  
509 # Generating the string consisting of [ attr="value"] pairs
510  
511 my $attrs_text;
512  
513 foreach my $key (sort keys %$attrs) {
514 my $str = $attrs->{$key};
515  
516 my $tagpath = $path.'@'.$str;
517  
518 $self->process_text_node($tagpath, $attrs, \$str, $callbackref, $lang, undef, undef);
519  
520 if ($lang) {
521 $attrs_text .= " $key=\"$str\"";
522 }
523 }
524  
525 # Construct and return the tag string with its inner xml
526  
527 if ($lang) {
528 if ($name eq '__CDATA') {
529 return '<![CDATA['.$inner_xml.']]>';
530 }
531  
532 if ($name eq '__COMMENT') {
533 return '<!--'.$inner_xml.'-->';
534 }
535  
536 if ($name eq '__PI') {
537 return '<?'.$inner_xml.'?>';
538 }
539  
540 if (($name ne '') && ($name ne '__ROOT')) {
541 return "<$name$attrs_text>$inner_xml</$name>";
542 }
543  
544 return $inner_xml;
545 }
546 }
547  
548 1;
« lib/Serge/Engine/Plugin/parse_chrome_json.pm ↑ Summary lib/Serge/Engine/Plugin/Transform/wrappertag.pm »