blib/lib/HTML/Object.pm untested

filter: Statementstmt 0.0% 0 / 458 Branchbran 0.0% 0 / 170 Conditioncond 0.0% 0 / 154 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 57 Podpod 0.0% 0 / 33 totaltotal 0.0% 0 / 872 CC 82 SCAR 38.7
CC
82
Cov
0%
import
132.0
sanity_check
110.0
parse_url
90.0
CRAP 47.7
1 ##----------------------------------------------------------------------------
2 ## HTML Object - ~/lib/HTML/Object.pm
3 ## Version v0.6.1
4 ## Copyright(c) 2026 DEGUEST Pte. Ltd.
5 ## Author: Jacques Deguest <jack@deguest.jp>
6 ## Created 2021/04/20
7 ## Modified 2026/03/29
8 ## All rights reserved
9 ##
10 ##
11 ## This program is free software; you can redistribute it and/or modify it
12 ## under the same terms as Perl itself.
13 ##----------------------------------------------------------------------------
14 package HTML::Object;
15 BEGIN
16 {
17 use strict;
18 use warnings;
19 use warnings::register;
20 use parent qw( Module::Generic );
21 use vars qw( $DICT $LINK_ELEMENTS $FATAL_ERROR $GLOBAL_DOM $VERSION );
22 use curry;
23 use Encode ();
24 use Filter::Util::Call;
25 use HTML::Object::Closing;
26 use HTML::Object::Comment;
27 use HTML::Object::Declaration;
28 use HTML::Object::Document;
29 use HTML::Object::Element;
30 use HTML::Object::Space;
31 use HTML::Object::Text;
32 use HTML::Parser;
33 use JSON;
34 use Module::Generic::File qw( file );
35 use Scalar::Util ();
36 our $VERSION = 'v0.6.1';
37 our $DICT = {};
38 our $LINK_ELEMENTS = {};
39 our $FATAL_ERROR = 0;
40 };
41  
42 use strict;
43 use warnings;
44  
45 {
46 my $me = file( __FILE__ );
47 my $path = $me->parent;
48 my $dict_json = 'html_tags_dict.json';
49 my $tags_repo = $path->child( $dict_json );
50 if( $tags_repo->exists )
51 {
52 # try-catch
53 local $@;
54 eval
55 {
56 my $json = $tags_repo->load_utf8 ||
57 die( "Unable to open html tags json dictionary \"$tags_repo\": ", $tags_repo->error, "\n" );
58 my $j = JSON->new->relaxed;
59 my $hash = $j->decode( $json );
60 die( "No html tags found inside dictionary file \"$tags_repo\"\n" ) if( !scalar( keys( %{$hash->{dict}} ) ) );
61 $DICT = $hash->{dict};
62 for( keys( %$DICT ) )
63 {
64 if( exists( $DICT->{ $_ }->{link_in} ) )
65 {
66 $LINK_ELEMENTS->{ $_ } = $DICT->{ $_ }->{link_in};
67 }
68 }
69 };
70 if( $@ )
71 {
72 die( "Fatal error occurred while trying to load html tags json dictionary \"$tags_repo\": $@\n" );
73 }
74 }
75 else
76 {
77 die( "Missing core file \"$dict_json\"\n" );
78 }
79 }
80  
81 sub import
82 {
83 my $class = shift( @_ );
84 my $hash = {};
85 for( my $i = 0; $i < scalar( @_ ); $i++ )
86 {
87 if( $_[$i] eq 'debug' ||
88 $_[$i] eq 'debug_code' ||
89 $_[$i] eq 'debug_file' ||
90 $_[$i] eq 'fatal_error' ||
91 $_[$i] eq 'global_dom' ||
92 $_[$i] eq 'try_catch' ||
93 $_[$i] eq 'xquery' )
94 {
95 $hash->{ $_[$i] } = $_[$i+1];
96 CORE::splice( @_, $i, 2 );
97 $i--;
98 }
99 }
100
101 {
102 local $Exporter::ExportLevel = 1;
103 Exporter::import( $class, @_ );
104 }
105 $hash->{debug} = 0 if( !CORE::exists( $hash->{debug} ) );
106 $hash->{global_dom} = 0 if( !CORE::exists( $hash->{global_dom} ) );
107 $hash->{debug_code} = 0 if( !CORE::exists( $hash->{debug_code} ) );
108 $hash->{fatal_error} = 0 if( !CORE::exists( $hash->{fatal_error} ) );
109 $hash->{try_catch} = 0 if( !CORE::exists( $hash->{try_catch} ) );
110 if( $hash->{fatal_error} )
111 {
112 $FATAL_ERROR = 1;
113 }
114
115 if( $hash->{try_catch} )
116 {
117 require Nice::Try;
118 Nice::Try->export_to_level( 1, @_ );
119 }
120
121 if( $hash->{global_dom} || $hash->{xquery} )
122 {
123 Filter::Util::Call::filter_add( bless( $hash => ( ref( $class ) || $class ) ) );
124 require HTML::Object::XQuery;
125 HTML::Object::XQuery->export_to_level( 1, @_ );
126 if( $hash->{global_dom} )
127 {
128 # Same as Firefox, Chrome or Safari do: default dom for blank page
129 our $GLOBAL_DOM = __PACKAGE__->new( debug => $hash->{debug} )->parse( <<EOT );
130 <html><head></head><body></body></html>
131 EOT
132 }
133 }
134 }
135  
136 sub filter
137 {
138 my( $self ) = @_ ;
139 my( $status, $last_line );
140 my $line = 0;
141 my $code = '';
142 if( !$self->{global_dom} )
143 {
144 Filter::Util::Call::filter_del();
145 $status = 1;
146 return( $status );
147 }
148 while( $status = Filter::Util::Call::filter_read() )
149 {
150 return( $status ) if( $status < 0 );
151 $line++;
152 if( /^__(?:DATA|END)__/ )
153 {
154 last;
155 }
156
157 s{
158 (?<!\\)\$\(
159 }
160 {
161 "xq("
162 }gexs;
163 if( $self->{xquery} )
164 {
165 s{
166 (?<!\\)\$\.([a-zA-Z]+)
167 }
168 {
169 "xQuery->$1"
170 }gexs;
171 }
172 }
173 if( $self->{debug_file} )
174 {
175 if( open( my $fh, ">$self->{debug_file}" ) )
176 {
177 binmode( $fh, ':utf8' );
178 print( $fh $_ );
179 close( $fh );
180 }
181 }
182 return( $line );
183 }
184  
185 sub init
186 {
187 my $self = shift( @_ );
188 $self->{_init_strict_use_sub} = 1;
189 $self->{_exception_class} = 'HTML::Object::Exception' unless( CORE::exists( $self->{_exception_class} ) );
190 $self->SUPER::init( @_ ) || return( $self->pass_error );
191 my $p = HTML::Parser->new(
192 api_version => 3,
193 start_h => [ $self->curry::add_start, 'self, tagname, attr, attrseq, text, column, line, offset, offset_end'],
194 end_h => [ $self->curry::add_end, 'self, tagname, attr, attrseq, text, column, line, offset, offset_end' ],
195 marked_sections => 1,
196 comment_h => [ $self->curry::add_comment, 'self, text, column, line, offset, offset_end'],
197 declaration_h => [ $self->curry::add_declaration, 'self, text, column, line, offset, offset_end'],
198 default_h => [ $self->curry::add_default, 'self, tagname, attr, attrseq, text, column, line, offset, offset_end'],
199 text_h => [ $self->curry::add_text, 'self, text, column, line, offset, offset_end'],
200 # This is not activated, because as per the documentation, this will call an 'end tag' caller, and this could imply <br></br> for other unknown tags, whereas with <br /> we know for sure this is an empty tag
201 # empty_element_tags => 1,
202 unbroken_text => 1,
203 );
204 $self->{document} = '';
205 $self->{current_parent} = '';
206 $self->{_parser} = $p;
207 $self->{_elems} = [];
208 return( $self );
209 }
210  
211 sub add_comment
212 {
213 my $self = shift( @_ );
214 my @args = @_;
215 my $opts = {};
216 my @p = qw( p raw col line offset offset_end );
217 @$opts{ @p } = @args;
218 my $parent = $self->current_parent;
219 my $val = $opts->{raw};
220 $val =~ s,^\<\!\-\-|\-\-\>$,,gs;
221 my $e = $self->new_comment({
222 column => $opts->{col},
223 line => $opts->{line},
224 offset => $opts->{offset},
225 original => $opts->{raw},
226 parent => $parent,
227 value => $val,
228 debug => $self->debug,
229 }) || return;
230 $parent->children->push( $e );
231 return( $e );
232 }
233  
234 sub add_declaration
235 {
236 my $self = shift( @_ );
237 my @args = @_;
238 my $opts = {};
239 my @p = qw( p raw col line offset offset_end );
240 @$opts{ @p } = @args;
241 my $parent = $self->current_parent;
242 return if( !$self->_is_a( $parent => 'HTML::Object::DOM::Document' ) );
243 my $e = $self->new_declaration({
244 column => $opts->{col},
245 line => $opts->{line},
246 offset => $opts->{offset},
247 original => $opts->{raw},
248 parent => $parent,
249 debug => $self->debug,
250 });
251 # $parent->children->push( $e );
252 $self->document->declaration( $e );
253 $parent->children->push( $e );
254 return( $e );
255 }
256  
257 sub add_default
258 {
259 my $self = shift( @_ );
260 my @args = @_;
261 my $opts = {};
262 my @p = qw( p tag attr seq raw col line offset offset_end );
263 @$opts{ @p } = @args;
264 return if( !CORE::length( $opts->{raw} ) && !defined( $opts->{tag} ) );
265 # Unknown tag, so we check if there is a "/>" to determine if this is an empty (void) tag or not
266 my $attr = $opts->{attr};
267 my $def = {};
268 $def->{is_empty} = exists( $attr->{'/'} ) ? 1 : 0;
269 my $parent = $self->current_parent;
270 if( !length( $opts->{tag} ) )
271 {
272 my @args_keys = qw( p raw col line offset offset_end );
273 return( $self->add_text( @$opts{ @args_keys } ) );
274 }
275 # Check the current parent and see if we need to close it.
276 # If this new tag is a non-empty tag (i.e. non-void) and the current parent has not been closed,
277 # implicitly close it now, by setting that tag's parent as the current parent
278 # This is what Mozilla does:
279 # Ref: <https://bugzilla.mozilla.org/show_bug.cgi?id=820926>
280 # NOTE This needs to be done in post processing not during initial parsing, because at this point in the process we have not yet seen the closing tag, and we might see it later, so making guesses here is ill-advised.
281 # if( !$parent->is_closed &&
282 # !$def->{is_empty} &&
283 # $parent &&
284 # !$parent->isa( 'HTML::Object::Document' ) &&
285 # $parent->tag ne 'html' )
286 # {
287 # $parent = $parent->parent;
288 # }
289 my $e = $self->new_element({
290 attributes => $opts->{attr},
291 attributes_sequence => $opts->{seq},
292 column => $opts->{col},
293 is_empty => $def->{is_empty},
294 line => $opts->{line},
295 offset => $opts->{offset},
296 original => $opts->{raw},
297 parent => $parent,
298 tag => $opts->{tag},
299 debug => $self->debug,
300 }) || return;
301 $parent->children->push( $e );
302 if( !$def->{is_empty} )
303 {
304 $self->current_parent( $e );
305 }
306 return( $e );
307 }
308  
309 sub add_end
310 {
311 my $self = shift( @_ );
312 my @args = @_;
313 my $opts = {};
314 my @p = qw( p tag attr seq raw col line offset offset_end );
315 @$opts{ @p } = @args;
316 my $me = $self->current_parent;
317 my $parent = $me->parent;
318 if( $opts->{tag} ne $me->tag )
319 {
320 warn( "Oops, something is wrong in the parsing. I was expecting a closing tag for \"", $me->tag, "\" that started at line \"", $me->line, "\" but instead found a closing tag for \"$opts->{tag}\" at line \"$opts->{line}\" and column \"$opts->{col}\": $opts->{raw}\n" ) if( $self->_warnings_is_enabled );
321 }
322 else
323 {
324 my $e = $self->new_closing({
325 attributes => $opts->{attr},
326 attributes_sequence => $opts->{seq},
327 column => $opts->{col},
328 line => $opts->{line},
329 offset => $opts->{offset},
330 original => $opts->{raw},
331 tag => $opts->{tag},
332 debug => $self->debug,
333 }) || return;
334 $me->is_closed(1);
335 $me->close_tag( $e );
336 # $parent->children->push( $e );
337 $self->current_parent( $parent );
338 }
339 }
340  
341 sub add_space
342 {
343 my $self = shift( @_ );
344 my $opts = $self->_get_args_as_hash( @_ );
345 my $parent = $self->current_parent;
346 my $e = $self->new_space( $opts ) || return( $self->pass_error );
347 $parent->children->push( $e );
348 return( $e );
349 }
350  
351 sub add_start
352 {
353 my $self = shift( @_ );
354 my @args = @_;
355 my $opts = {};
356 my @p = qw( p tag attr seq raw col line offset offset_end );
357 @$opts{ @p } = @args;
358 my $parent = $self->current_parent;
359 if( $opts->{tag} =~ s,/,, )
360 {
361 $opts->{attr}->{'/'} = '/';
362 }
363 my $def = $self->get_definition( $opts->{tag} );
364 # Make some easy guess
365 if( !scalar( keys( %$def ) ) )
366 {
367 $def->{is_empty} = 1 if( CORE::exists( $opts->{attr}->{'/'} ) );
368 # "Return HTMLUnknownElement"
369 # <https://html.spec.whatwg.org/multipage/dom.html#htmlunknownelement>
370 $def->{class} = 'HTML::Object::DOM::Unknown';
371 }
372 $def->{is_empty} = 0 unless( CORE::exists( $def->{is_empty} ) );
373 # Check the current parent and see if we need to close it.
374 # If this new tag is a non-empty tag (i.e. non-void) and the current parent has not been closed,
375 # implicitly close it now, by setting that tag's parent as the current parent
376 # This is what Mozilla does:
377 # Ref: <https://bugzilla.mozilla.org/show_bug.cgi?id=820926>
378 # NOTE This needs to be done in post processing not during initial parsing, because at this point in the process we have not yet seen the closing tag, and we might see it later, so making guesses here is ill-advised.
379 # if( !$parent->is_closed &&
380 # !$def->{is_empty} &&
381 # $parent &&
382 # !$parent->isa( 'HTML::Object::Document' ) &&
383 # $parent->tag ne 'html' )
384 # {
385 # $parent = $parent->parent;
386 # }
387 $def->{class} //= '';
388 my $e;
389 my $params =
390 {
391 attributes => $opts->{attr},
392 attributes_sequence => $opts->{seq},
393 column => $opts->{col},
394 is_empty => $def->{is_empty},
395 line => $opts->{line},
396 offset => $opts->{offset},
397 original => $opts->{raw},
398 parent => $parent,
399 tag => $opts->{tag},
400 # and
401 debug => $self->debug,
402 };
403
404 # If this tag is handled by a special class, instantiate the object by this class
405 if( $def->{class} )
406 {
407 $e = $self->new_special( $def->{class} => $params ) || return;
408 }
409 else
410 {
411 $e = $self->new_element( $params ) || return;
412 }
413 $parent->children->push( $e );
414 # If this element is an element that, by nature, can contain other elements we mark it as the last element seen so it can be used as a parent. When we close it, we switch the parent to its parent .
415 if( !$def->{is_empty} )
416 {
417 $self->current_parent( $e );
418 }
419 return( $e );
420 }
421  
422 sub add_text
423 {
424 my $self = shift( @_ );
425 my @args = @_;
426 my $opts = {};
427 my @p = qw( p raw col line offset offset_end );
428 @$opts{ @p } = @args;
429 my $parent = $self->current_parent ||
430 return( $self->error( "You must create a document first using the new_document() method first before adding text." ) );
431 my $e;
432 # Text can be either some space or letters, digits (non-space characters)
433 # HTML::Parser does not make the difference, but we do
434 if( $opts->{raw} =~ /^[[:blank:]\h\v]*$/ )
435 {
436 $e = $self->add_space(
437 original => $opts->{raw},
438 column => $opts->{col},
439 line => $opts->{line},
440 offset => $opts->{offset},
441 parent => $parent,
442 value => $opts->{raw},
443 debug => $self->debug,
444 # No 'value' set on purpose, because if none, then 'original' will be used by
445 # as_string
446 ) || return;
447 }
448 else
449 {
450 $e = $self->new_text({
451 column => $opts->{col},
452 line => $opts->{line},
453 offset => $opts->{offset},
454 original => $opts->{raw},
455 parent => $parent,
456 value => $opts->{raw},
457 debug => $self->debug,
458 }) || return;
459 $parent->children->push( $e );
460 }
461 return( $e );
462 }
463  
464 sub current_parent { return( shift->_set_get_object_without_init( 'current_parent', 'HTML::Object::Element', @_ ) ); }
465  
466 sub dictionary { return( $DICT ); }
467  
468 sub document { return( shift->_set_get_object( 'document', 'HTML::Object::Document', @_ ) ); }
469  
470 sub get_definition
471 {
472 my $self = shift( @_ );
473 my $tag = shift( @_ );
474 return( $self->error( "No tag was provided to get its definition." ) ) if( !length( $tag ) );
475 # Just to be sure
476 $tag = lc( $tag );
477 return( {} ) if( !exists( $DICT->{ $tag } ) );
478 return( $DICT->{ $tag } );
479 }
480  
481 sub new_closing
482 {
483 my $self = shift( @_ );
484 my $e = HTML::Object::Closing->new( @_ ) ||
485 return( $self->pass_error( HTML::Object::Closing->error ) );
486 return( $e );
487 }
488  
489 sub new_comment
490 {
491 my $self = shift( @_ );
492 my $e = HTML::Object::Comment->new( @_ ) ||
493 return( $self->pass_error( HTML::Object::Comment->error ) );
494 return( $e );
495 }
496  
497 sub new_declaration
498 {
499 my $self = shift( @_ );
500 my $e = HTML::Object::Declaration->new( @_ ) ||
501 return( $self->pass_error( HTML::Object::Declaration->error ) );
502 return( $e );
503 }
504  
505 sub new_document
506 {
507 my $self = shift( @_ );
508 my $e = HTML::Object::Document->new( @_ ) ||
509 return( $self->pass_error( HTML::Object::Document->error ) );
510 return( $e );
511 }
512  
513 sub new_element
514 {
515 my $self = shift( @_ );
516 my $e = HTML::Object::Element->new( @_ ) ||
517 return( $self->pass_error( HTML::Object::Element->error ) );
518 return( $e );
519 }
520  
521 sub new_space
522 {
523 my $self = shift( @_ );
524 my $e = HTML::Object::Space->new( @_ ) ||
525 return( $self->pass_error( HTML::Object::Space->error ) );
526 return( $e );
527 }
528  
529 sub new_special
530 {
531 my $self = shift( @_ );
532 my $class = shift( @_ );
533 $self->_load_class( $class ) || return( $self->pass_error );
534 my $e = $class->new( @_ ) || return( $self->pass_error( $class->error ) );
535 return( $e );
536 }
537  
538 sub new_text
539 {
540 my $self = shift( @_ );
541 my $e = HTML::Object::Text->new( @_ ) ||
542 return( $self->pass_error( HTML::Object::Text->error ) );
543 return( $e );
544 }
545  
546 sub parse
547 {
548 my $self = shift( @_ );
549 my $this = shift( @_ );
550 my $opts = $self->_get_args_as_hash( @_ );
551 if( ref( $this ) eq 'CODE' || ref( $this ) eq 'GLOB' || "$this" =~ /<\w+/ || CORE::length( "$this" ) > 1024 )
552 {
553 return( $self->parse_data( $this, $opts ) );
554 }
555 elsif( ref( $this ) )
556 {
557 return( $self->error( "I was provided a reference (", overload::StrVal( $this ), ") to parse html data, but I do not know what to do with it." ) );
558 }
559 else
560 {
561 return( $self->parse_file( $this, $opts ) );
562 }
563 }
564  
565 sub parse_data
566 {
567 my $self = shift( @_ );
568 my $html = shift( @_ );
569 my $opts = $self->_get_args_as_hash( @_ );
570 $html = "$html";
571 # try-catch
572 local $@;
573 eval
574 {
575 if( $opts->{utf8} )
576 {
577 $html = Encode::decode( 'utf8', $html, Encode::FB_CROAK );
578 }
579 };
580 if( $@ )
581 {
582 return( $self->error( "Error found while utf8 decoding ", length( $html ), " bytes of html data provided: $@" ) );
583 }
584
585 my $e;
586 if( length( $self->{current_parent} ) && $self->_is_object( $self->{current_parent} ) )
587 {
588 $e = $self->current_parent;
589 }
590 else
591 {
592 $e = $self->new_document( debug => $self->debug );
593 $self->document( $e );
594 $self->current_parent( $e );
595 if( $self->isa( 'HTML::Object::DOM' ) )
596 {
597 if( my $code = $self->onload )
598 {
599 $e->onload( $code );
600 }
601 if( my $code = $self->onreadystatechange )
602 {
603 $e->onreadystatechange( $code );
604 }
605 }
606 }
607 my $doc = $self->document;
608 my $p = $self->parser;
609 $self->_set_state( 'loading' => $doc );
610 $p->parse( $html );
611 $self->_set_state( 'interactive' => $doc );
612 $self->post_process( $e );
613 $self->_set_state( 'complete' => $doc );
614 $p->eof;
615 return( $e );
616 }
617  
618 sub parse_file
619 {
620 my $self = shift( @_ );
621 my $file = shift( @_ ) || return( $self->error( "No file to parse was provided." ) );
622 my $opts = $self->_get_args_as_hash( @_ );
623 # On, by default, if not provided
624 $opts->{utf8} //= 1;
625 my $f = $self->new_file( $file );
626 if( !$f->exists )
627 {
628 return( $self->error( "File to parse \"$file\" does not exist." ) );
629 }
630 elsif( $f->is_empty )
631 {
632 return( $self->error( "File to parse \"$file\" is empty." ) );
633 }
634 my $params = {};
635 $params->{binmode} = 'utf8' if( $opts->{utf8} );
636 my $io = $f->open( '<', $params ) ||
637 return( $self->error( "Unable to open file to parse \"$file\": ", $f->error ) );
638 my $e = $self->new_document( _last_modified => $f->mtime );
639 $self->document( $e );
640 if( $self->isa( 'HTML::Object::DOM' ) )
641 {
642 if( my $code = $self->onload )
643 {
644 $e->onload( $code );
645 }
646 if( my $code = $self->onreadystatechange )
647 {
648 $e->onreadystatechange( $code );
649 }
650 }
651 $self->current_parent( $e );
652 $self->_set_state( 'loading' => $e );
653 my $p = $self->parser;
654 $p->parse_file( $io );
655 $io->close;
656 $self->_set_state( 'interactive' => $e );
657 $self->post_process( $e );
658 $self->_set_state( 'complete' => $e );
659 return( $e );
660 }
661  
662 sub parse_url
663 {
664 my $self = shift( @_ );
665 my $uri;
666 if( ( scalar( @_ ) == 1 && ref( $_[0] ) ne 'HASH' ) ||
667 ( scalar( @_ ) > 1 &&
668 (
669 ( @_ % 2 ) ||
670 ( scalar( @_ ) == 2 && ref( $_[1] ) eq 'HASH' )
671 )
672 ) )
673 {
674 $uri = shift( @_ );
675 }
676 my $opts = $self->_get_args_as_hash( @_ );
677 $uri = CORE::delete( $opts->{uri} ) if( defined( $opts->{uri} ) && CORE::length( $opts->{uri} ) );
678 if( !$self->_load_class( 'LWP::UserAgent', { version => '6.49' } ) )
679 {
680 return( $self->error( "LWP::UserAgent version 6.49 or higher is required to use load()" ) );
681 }
682 if( !$self->_load_class( 'URI', { version => '1.74' } ) )
683 {
684 return( $self->error( "URI version 1.74 or higher is required to use load()" ) );
685 }
686 $opts->{timeout} //= 10;
687 # try-catch
688 local $@;
689 eval
690 {
691 $uri = URI->new( "$uri" );
692 };
693 if( $@ )
694 {
695 return( $self->error( "Bad url provided \"$uri\": $@" ) );
696 }
697
698 my $content;
699 my $resp;
700 # try-catch
701 eval
702 {
703 my $ua = LWP::UserAgent->new(
704 agent => "HTML::Object/$VERSION",
705 timeout => $opts->{timeout},
706 );
707 $resp = $ua->get( $uri, ( CORE::exists( $opts->{headers} ) && defined( $opts->{headers} ) && ref( $opts->{headers} ) eq 'HASH' && scalar( keys( %{$opts->{headers}} ) ) ) ? %{$opts->{headers}} : () );
708 $content = $resp->decoded_content;
709 };
710 if( $resp->header( 'Client-Warning' ) || !$resp->is_success )
711 {
712 return( $self->error({
713 code => $resp->code,
714 message => $resp->message,
715 }) );
716 }
717 $self->response( $resp );
718 if( $@ )
719 {
720 return( $self->error( "Error making a GET request to $uri: $@" ) );
721 }
722 my $doc = $self->parse_data( $content );
723 $doc->uri( $uri );
724 return( $doc );
725 }
726  
727 sub parser { return( shift->_set_get_object_without_init( '_parser', 'HTML::Parser', @_ ) ); }
728  
729 sub post_process
730 {
731 my $self = shift( @_ );
732 my $elem = shift( @_ );
733 return if( !$self->_is_object( $elem ) );
734 return if( !$elem->isa( 'HTML::Object::Element' ) );
735 # Crawl through the tree and look for unclosed tags
736 $elem->children->foreach(sub
737 {
738 my $e = shift( @_ );
739 return(1) if( $e->isa( 'HTML::Object::Closing' ) || $e->tag->substr( 0, 1 ) eq '_' );
740 if( $e->is_empty && $e->children->length )
741 {
742 # It should be empty, but has some children
743 }
744 elsif( $e->is_empty && !$e->attributes->exists( '/' ) )
745 {
746 # Is empty, but does not end with />
747 }
748 elsif( !$e->is_empty && !$e->is_closed )
749 {
750 my $def = $self->get_definition( $e->tag );
751 if( !$def->{is_empty} )
752 {
753 # Is an enclosing tag, but it has not been closed
754 }
755 else
756 {
757 # Is an empty (void) tag, but it did not end with /
758 }
759 }
760 $self->post_process( $e ) if( !$e->is_empty );
761 });
762 return( $self );
763 }
764  
765 sub response { return( shift->_set_get_object_without_init( 'response', 'HTTP::Response', @_ ) ); }
766  
767 sub sanity_check
768 {
769 my $self = shift( @_ );
770 my $elem = shift( @_ );
771 return if( !$self->_is_object( $elem ) );
772 return if( !$elem->isa( 'HTML::Object::Element' ) );
773 # Crawl through the tree and look for unclosed tags
774 $elem->children->foreach(sub
775 {
776 my $e = shift( @_ );
777 return(1) if( $e->isa( 'HTML::Object::Closing' ) || $e->tag->substr( 0, 1 ) eq '_' );
778 if( $e->is_empty && $e->children->length )
779 {
780 printf( STDOUT "Tag \"%s\" should be empty (void), but it has %d children.\n", $e->tag, $e->children->length );
781 }
782 elsif( $e->is_empty && !$e->attributes->exists( '/' ) )
783 {
784 printf( STDOUT "Tag \"%s\" at line %d at row %d is an empty (void) tag, but it did not end with />\n", $e->tag, $e->line, $e->column );
785 }
786 elsif( !$e->is_empty && $e->attributes->exists( '/' ) )
787 {
788 printf( STDOUT "Tag \"%s\" at line %d at row %d is marked as non-empty (non-void), but it ends with />\n", $e->tag, $e->line, $e->column );
789 }
790 elsif( !$e->is_empty && !$e->is_closed )
791 {
792 my $def = $self->get_definition( $e->tag );
793 if( !$def->{is_empty} )
794 {
795 printf( STDOUT "Tag \"%s\" at line %d at row %d is an enclosing tag, but it has not been closed.\n", $e->tag, $e->line, $e->column );
796 }
797 else
798 {
799 printf( STDOUT "Tag \"%s\" at line %d at row %d is an empty (void) tag, but it did not end with />\n", $e->tag, $e->line, $e->column );
800 }
801 }
802 $self->sanity_check( $e ) if( !$e->is_empty );
803 });
804 return( $self );
805 }
806  
807 sub set_dom
808 {
809 my( $this, $html ) = @_;
810 if( defined( $html ) )
811 {
812 if( Scalar::Util::blessed( $html ) && $html->isa( 'HTML::Object::Document' ) )
813 {
814 $GLOBAL_DOM = $html;
815 }
816 elsif( CORE::length( $html ) )
817 {
818 $GLOBAL_DOM = $this->new->parse( $html );
819 }
820 }
821 return( $this );
822 }
823  
824 sub _set_state
825 {
826 my $self = shift( @_ );
827 my( $state, $elem ) = @_;
828 # This feature is only applicable for HTML::Object::DOM
829 return( $self ) unless( $self->isa( 'HTML::Object::DOM' ) );
830 # ... and only for documents
831 return if( !defined( $elem ) || !$self->_is_a( $elem => 'HTML::Object::DOM::Document' ) );
832 $elem->readyState( $state );
833 require HTML::Object::Event;
834 my $event = HTML::Object::Event->new( 'readystate',
835 bubbles => 0,
836 cancelable => 0,
837 detail => { 'state' => $state, document => $elem },
838 target => $elem,
839 );
840 # $elem->dispatchEvent( $event );
841 if( my $eh = $elem->onreadystatechange )
842 {
843 local $_ = $elem;
844 my $code = $eh->code;
845 warn( "Value for event handler '$code' is not a code reference.\n" ) if( ref( $code ) ne 'CODE' );
846 $code->( $event ) if( ref( $code ) eq 'CODE' );
847 }
848 if( $state eq 'complete' && ( my $code = $elem->onload ) )
849 {
850 local $_ = $elem;
851 $code->( $event );
852 }
853 return( $self );
854 }
855  
856 1;
857 # NOTE: POD
858 __END__
859  
860 =encoding utf-8
861  
862 =head1 NAME
863  
864 HTML::Object - HTML Parser, Modifier and Query Interface
865  
866 =head1 SYNOPSIS
867  
868 use HTML::Object;
869 my $p = HTML::Object->new( debug => 5 );
870 my $doc = $p->parse( $file, { utf8 => 1 } ) || die( $p->error, "\n" );
871 print $doc->as_string;
872  
873 or, using the HTML DOM implementation same as the Web API:
874  
875 use HTML::Object::DOM global_dom => 1;
876 # then you can also use HTML::Object::XQuery for jQuery like DOM manipulation
877 my $p = HTML::Object::DOM->new;
878 my $doc = $p->parse_data( $some_html ) || die( $p->error, "\n" );
879 $('div.inner')->after( "<p>Test</p>" );
880  
881 You can also enable access to L<xQuery> class functions with the C<$.> prefix, like jQuery, by passing the C<xquery> option:
882  
883 use HTML::Object::DOM xquery => 1;
884 # or
885 # use HTML::Object::DOM global_dom => 1, xquery => 1;
886 $.each( $array_ref, sub
887 {
888 my( $index, $value ) = @_;
889 # Do something
890 });
891  
892 # returns an HTML::Object::DOM::Collection
893 my $divs = $doc->getElementsByTagName( 'div' );
894 my $new = $doc->createElement( 'div' );
895 $new->setAttribute( id => 'newDiv' );
896 $divs->[0]->parent->replaceChild( $new, $divs->[0] );
897 # etc.
898  
899 To enable fatal error and also implement try-catch (using L<Nice::Try>) :
900  
901 use HTML::Object fatal_error => 1, try_catch => 1;
902  
903 =head1 VERSION
904  
905 v0.6.1
906  
907 =head1 DESCRIPTION
908  
909 This module is yet another HTML parser, manipulation and query interface, but probably the most comprehensive one. It uses the C parser from L<HTML::Parser> and has the unique particularity that it does not try to decode the entire html document tree only to re-encode it when printing out its data as string like so many other html parsers out there do. Instead, it modifies only the parts required. The rest is returned exactly as it was found in the HTML. This is faster and safer.
910  
911 This module contains 144 modules to closely implement the HTML standard as documented on L<Mozilla documentation|https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API>.
912  
913 It uses an external json data dictionary file of html tags (C<html_tags_dict.json>).
914  
915 There are 3 ways to manipulate and query the html data:
916  
917 =over 4
918  
919 =item 1. L<HTML::Object::Element>
920  
921 This is lightweight and simple
922  
923 =item 2. L<HTML::Object::DOM>
924  
925 This is an alternative HTML parser also based on L<HTML::Parser>, and that implements fully the Web API with DOM (Data Object Model), so you can query the HTML with perl equivalent to JavaScript methods of the Web API. It has been designed to be strictly identical to the Web API.
926  
927 =item 3. L<HTML::Object::XQuery>
928  
929 This interface provides a jQuery like API and requires the use of L<HTML::Object::DOM>. However, this is not designed to be a perl implementation of JavaScript, but rather a perl implementation of DOM manipulation methods found in jQuery.
930  
931 =back
932  
933 Note that this interface does not enforce HTML standard. It is up to you the developer to decide what value to use and where the HTML elements should go in the HTML tree and what to do with it.
934  
935 =head1 METHODS
936  
937 =head2 new
938  
939 Instantiate a new L<HTML::Object> object.
940  
941 You need to instantiate a new object prior to parse any new document. It cannot be re-used to parse another document, or if you really wanted to, you would first need to unset L</document> and unset L</current_parent>:
942  
943 $p->document( undef );
944 $p->current_parent( undef );
945  
946 But, it is just as fast to do:
947  
948 $p = HTML::Object->new;
949  
950 =head2 add_comment
951  
952 This is a parser method called that will add a comment to the stack of html elements.
953  
954 =head2 add_declaration
955  
956 This is a parser method called that will add a declaration to the stack of html elements.
957  
958 =head2 add_default
959  
960 This is a parser method called that will add a default html tag to the stack of html elements.
961  
962 =head2 add_end
963  
964 This is a parser method called that will add a closing html tag to the stack of html elements.
965  
966 =head2 add_space
967  
968 This is a parser method called that will add a space to the stack of html elements.
969  
970 =head2 add_start
971  
972 This is a parser method called that will add a starting html tag to the stack of html elements.
973  
974 =head2 add_text
975  
976 This is a parser method called that will add a text to the stack of html elements.
977  
978 =head2 current_parent
979  
980 Sets or gets the current parent, which must be an L<HTML::Object::Element> object or an inheriting class.
981  
982 =head2 dictionary
983  
984 Returns an hash reference containing the HTML tags dictionary. Its structure is:
985  
986 =over 4
987  
988 =item * dict
989  
990 This property reflects an hash containing all the known tags. Each tag has the following possible properties:
991  
992 =over 8
993  
994 =item * description
995  
996 String
997  
998 =item * is_deprecated
999  
1000 Boolean value
1001  
1002 =item * is_empty
1003  
1004 Boolean value
1005  
1006 =item * is_inline
1007  
1008 Boolean value
1009  
1010 =item * is_svg
1011  
1012 Boolean value that describes whether this is a tag dedicated to svg.
1013  
1014 =item * link_in
1015  
1016 Array reference of HTML attributes containing links
1017  
1018 =item * ref
1019  
1020 The reference URL to the online web documentation for this tag.
1021  
1022 =back
1023  
1024 =item * meta
1025  
1026 This property holds an hash reference containing the following meta information:
1027  
1028 =over 8
1029  
1030 =item * author
1031  
1032 String
1033  
1034 =item * updated
1035  
1036 ISO 8601 datetime
1037  
1038 =item * version
1039  
1040 Version number
1041  
1042 =back
1043  
1044 =back
1045  
1046 =head2 document
1047  
1048 Sets or gets the document L<HTML::Object::Document> object.
1049  
1050 =head2 get_definition
1051  
1052 Get the hash definition for a given tag (case does not matter).
1053  
1054 The tags definition is taken from the external file C<html_tags_dict.json> that is provided with this package.
1055  
1056 =head2 new_closing
1057  
1058 Creates and returns a new closing html element L<HTML::Object::Closing>, passing it any arguments provided.
1059  
1060 =head2 new_comment
1061  
1062 Creates and returns a new closing html element L<HTML::Object::Comment>, passing it any arguments provided.
1063  
1064 =head2 new_declaration
1065  
1066 Creates and returns a new closing html element L<HTML::Object::Declaration>, passing it any arguments provided.
1067  
1068 =head2 new_document
1069  
1070 Creates and returns a new closing html element L<HTML::Object::Document>, passing it any arguments provided.
1071  
1072 =head2 new_element
1073  
1074 Creates and returns a new closing html element L<HTML::Object::Element>, passing it any arguments provided.
1075  
1076 =head2 new_space
1077  
1078 Creates and returns a new closing html element L<HTML::Object::Space>, passing it any arguments provided.
1079  
1080 =head2 new_special
1081  
1082 Provided with an HTML tag class name and hash or hash reference of options and this will load that class and instantiate an object passing it the options provided. It returns the object thus Instantiated.
1083  
1084 This is used to instantiate object for special class to handle certain HTML tag, such as C<a>
1085  
1086 =head2 new_text
1087  
1088 Creates and returns a new closing html element L<HTML::Object::Text>, passing it any arguments provided.
1089  
1090 =head2 parse
1091  
1092 Provided with some C<data> (see below), and some options as hash or hash reference and this will parse it and return a new L<HTML::Object::Document> object.
1093  
1094 Possible accepted data are:
1095  
1096 =over 4
1097  
1098 =item I<code>
1099  
1100 L</parse_data> will be called with it.
1101  
1102 =item I<glob>
1103  
1104 L</parse_data> will be called with it.
1105  
1106 =item I<string>
1107  
1108 L</parse_file> will be called with it.
1109  
1110 =back
1111  
1112 Other reference will return an error.
1113  
1114 =head2 parse_data
1115  
1116 Provided with some C<data> and some options as hash or hash reference and this will parse the given data and return a L<HTML::Object::Document> object.
1117  
1118 If the option I<utf8> is provided, the C<data> received will be converted to utf8 using L<Encode/decode>. If an error occurs decoding the data into utf8, the error will be set as an L<Module::Generic::Exception> object and undef will be returned.
1119  
1120 =head2 parse_file
1121  
1122 Provided with a file path and some options as hash or hash reference and this will parse the file.
1123  
1124 If the option I<utf8> is provided, the file will be opened with L<perlfunc/binmode> set to C<utf8>
1125  
1126 It returns a new L<HTML::Object::Document>
1127  
1128 =head2 parse_url
1129  
1130 Provided with an URI supported by L<LWP::UserAgent> and this will issue a GET query and parse the resulting HTML data, and return a new L<HTML::Object::Document> or L<HTML::Object::DOM::Document> depending on which interface you use (either L<HTML::Object> or L<HTML::Object::DOM>.
1131  
1132 If an error occurred, this will set an L<error|Module::Generic/error> and return C<undef>.
1133  
1134 You can get the L<response|HTTP::Response> object with L</response>
1135  
1136 =head2 parser
1137  
1138 Sets or gets a L<HTML::Parser> object.
1139  
1140 =head2 post_process
1141  
1142 Provided with an L<HTML::Object::Element> and this will post process its parsing.
1143  
1144 =head2 response
1145  
1146 Get the latest L<HTTP::Response> object from the HTTP query made using L</parse_url>
1147  
1148 =head2 sanity_check
1149  
1150 Provided with an L<HTML::Object::Element> and this will perform some sanity checks and report the result on C<STDOUT>.
1151  
1152 =head2 set_dom
1153  
1154 Provided with a L<HTML::Object::Document> object and this sets the global variable C<$GLOBAL_DOM>. This is particularly useful when using L<HTML::Object::XQuery> to do things like:
1155  
1156 my $collection = $('div');
1157  
1158 =head1 CREDITS
1159  
1160 Throughout the documentation of this distribution, a lot of descriptions, references and examples have been borrowed from Mozilla. I have also contributed to improving their documentation by fixing bugs and typos on their site.
1161  
1162 =head1 AUTHOR
1163  
1164 Jacques Deguest E<lt>F<jack@deguest.jp>E<gt>
1165  
1166 =head1 SEE ALSO
1167  
1168 L<HTML::Object::DOM>, L<HTML::Object::Element>, L<HTML::Object::XQuery>
1169  
1170 =head1 COPYRIGHT & LICENSE
1171  
1172 Copyright (c) 2021 DEGUEST Pte. Ltd.
1173  
1174 You can use, copy, modify and redistribute this package and associated files under the same terms as Perl itself.
1175  
1176 =cut