Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1783 lines
67 KiB

  1. require 5;
  2. # Time-stamp: "2001-03-14 20:11:48 MST"
  3. package HTML::TreeBuilder;
  4. #TODO: maybe have it recognize higher versions of
  5. # Parser, and register the methods as subs?
  6. # Hm, but TreeBuilder wouldn't be subclassable, then.
  7. # TODO: document tweaks?
  8. # TODO: deprecate subclassing TreeBuilder?
  9. use strict;
  10. use integer; # vroom vroom!
  11. use vars qw(@ISA $VERSION $DEBUG);
  12. $VERSION = '3.11';
  13. # TODO: thank whoever pointed out the TEXTAREA bug
  14. # TODO: make require Parser of at least version... 2.27?
  15. # The one with the stop-parse. Then kill the whole stunting thing.
  16. #---------------------------------------------------------------------------
  17. # Make a 'DEBUG' constant...
  18. BEGIN {
  19. # We used to have things like
  20. # print $indent, "lalala" if $Debug;
  21. # But there were an awful lot of having to evaluate $Debug's value.
  22. # If we make that depend on a constant, like so:
  23. # sub DEBUG () { 1 } # or whatever value.
  24. # ...
  25. # print $indent, "lalala" if DEBUG;
  26. # Which at compile-time (thru the miracle of constant folding) turns into:
  27. # print $indent, "lalala";
  28. # or, if DEBUG is a constant with a true value, then that print statement
  29. # is simply optimized away, and doesn't appear in the target code at all.
  30. # If you don't believe me, run:
  31. # perl -MO=Deparse,-uHTML::TreeBuilder -e 'BEGIN { \
  32. # $HTML::TreeBuilder::DEBUG = 4} use HTML::TreeBuilder'
  33. # and see for yourself (substituting whatever value you want for $DEBUG
  34. # there).
  35. if(defined &DEBUG) {
  36. # Already been defined! Do nothing.
  37. } elsif($] < 5.00404) {
  38. # Grudgingly accomodate ancient (pre-constant) versions.
  39. eval 'sub DEBUG { $Debug } ';
  40. } elsif(!$DEBUG) {
  41. eval 'sub DEBUG () {0}'; # Make it a constant.
  42. } elsif($DEBUG =~ m<^\d+$>s) {
  43. eval 'sub DEBUG () { ' . $DEBUG . ' }'; # Make THAT a constant.
  44. } else { # WTF?
  45. warn "Non-numeric value \"$DEBUG\" in \$HTML::Element::DEBUG";
  46. eval 'sub DEBUG () { $DEBUG }'; # I guess.
  47. }
  48. }
  49. #---------------------------------------------------------------------------
  50. use HTML::Entities ();
  51. use HTML::Tagset 3.02 ();
  52. use HTML::Element ();
  53. use HTML::Parser ();
  54. @ISA = qw(HTML::Element HTML::Parser);
  55. # This looks schizoid, I know.
  56. # It's not that we ARE an element AND a parser.
  57. # We ARE an element, but one that knows how to handle signals
  58. # (method calls) from Parser in order to elaborate its subtree.
  59. # Legacy aliases:
  60. *HTML::TreeBuilder::isKnown = \%HTML::Tagset::isKnown;
  61. *HTML::TreeBuilder::canTighten = \%HTML::Tagset::canTighten;
  62. *HTML::TreeBuilder::isHeadElement = \%HTML::Tagset::isHeadElement;
  63. *HTML::TreeBuilder::isBodyElement = \%HTML::Tagset::isBodyElement;
  64. *HTML::TreeBuilder::isPhraseMarkup = \%HTML::Tagset::isPhraseMarkup;
  65. *HTML::TreeBuilder::isHeadOrBodyElement = \%HTML::Tagset::isHeadOrBodyElement;
  66. *HTML::TreeBuilder::isList = \%HTML::Tagset::isList;
  67. *HTML::TreeBuilder::isTableElement = \%HTML::Tagset::isTableElement;
  68. *HTML::TreeBuilder::isFormElement = \%HTML::Tagset::isFormElement;
  69. *HTML::TreeBuilder::p_closure_barriers = \@HTML::Tagset::p_closure_barriers;
  70. #==========================================================================
  71. # Two little shortcut constructors:
  72. sub new_from_file { # or from a FH
  73. my $class = shift;
  74. require Carp, Carp::croak("new_from_file takes only one argument")
  75. unless @_ == 1;
  76. require Carp, Carp::croak("new_from_file is a class method only")
  77. if ref $class;
  78. my $new = $class->new();
  79. $new->parse_file($_[0]);
  80. return $new;
  81. }
  82. sub new_from_content { # from any number of scalars
  83. my $class = shift;
  84. require Carp, Carp::croak("new_from_content is a class method only")
  85. if ref $class;
  86. my $new = $class->new();
  87. foreach my $whunk (@_) {
  88. $new->parse($whunk);
  89. last if $new->{'_stunted'}; # might as well check that.
  90. }
  91. $new->eof();
  92. return $new;
  93. }
  94. #---------------------------------------------------------------------------
  95. sub new { # constructor!
  96. my $class = shift;
  97. $class = ref($class) || $class;
  98. my $self = HTML::Element->new('html'); # Initialize HTML::Element part
  99. {
  100. # A hack for certain strange versions of Parser:
  101. my $other_self = HTML::Parser->new();
  102. %$self = (%$self, %$other_self); # copy fields
  103. # Yes, multiple inheritance is messy. Kids, don't try this at home.
  104. bless $other_self, "HTML::TreeBuilder::_hideyhole";
  105. # whack it out of the HTML::Parser class, to avoid the destructor
  106. }
  107. # The root of the tree is special, as it has these funny attributes,
  108. # and gets reblessed into this class.
  109. # Initialize parser settings
  110. $self->{'_implicit_tags'} = 1;
  111. $self->{'_implicit_body_p_tag'} = 0;
  112. # If true, trying to insert text, or any of %isPhraseMarkup right
  113. # under 'body' will implicate a 'p'. If false, will just go there.
  114. $self->{'_tighten'} = 1;
  115. # whether ignorable WS in this tree should be deleted
  116. $self->{'_implicit'} = 1; # to delete, once we find a real open-"html" tag
  117. $self->{'_element_class'} = 'HTML::Element';
  118. $self->{'_ignore_unknown'} = 1;
  119. $self->{'_ignore_text'} = 0;
  120. $self->{'_warn'} = 0;
  121. $self->{'_no_space_compacting'}= 0;
  122. $self->{'_store_comments'} = 0;
  123. $self->{'_store_pis'} = 0;
  124. $self->{'_store_declarations'} = 0;
  125. $self->{'_p_strict'} = 0;
  126. # Parse attributes passed in as arguments
  127. if(@_) {
  128. my %attr = @_;
  129. for (keys %attr) {
  130. $self->{"_$_"} = $attr{$_};
  131. }
  132. }
  133. # rebless to our class
  134. bless $self, $class;
  135. $self->{'_element_count'} = 1;
  136. # undocumented, informal, and maybe not exactly correct
  137. $self->{'_head'} = $self->insert_element('head',1);
  138. $self->{'_pos'} = undef; # pull it back up
  139. $self->{'_body'} = $self->insert_element('body',1);
  140. $self->{'_pos'} = undef; # pull it back up again
  141. return $self;
  142. }
  143. #==========================================================================
  144. sub _elem # universal accessor...
  145. {
  146. my($self, $elem, $val) = @_;
  147. my $old = $self->{$elem};
  148. $self->{$elem} = $val if defined $val;
  149. return $old;
  150. }
  151. # accessors....
  152. sub implicit_tags { shift->_elem('_implicit_tags', @_); }
  153. sub implicit_body_p_tag { shift->_elem('_implicit_body_p_tag', @_); }
  154. sub p_strict { shift->_elem('_p_strict', @_); }
  155. sub no_space_compacting { shift->_elem('_no_space_compacting', @_); }
  156. sub ignore_unknown { shift->_elem('_ignore_unknown', @_); }
  157. sub ignore_text { shift->_elem('_ignore_text', @_); }
  158. sub ignore_ignorable_whitespace { shift->_elem('_tighten', @_); }
  159. sub store_comments { shift->_elem('_store_comments', @_); }
  160. sub store_declarations { shift->_elem('_store_declarations', @_); }
  161. sub store_pis { shift->_elem('_store_pis', @_); }
  162. sub warn { shift->_elem('_warn', @_); }
  163. #==========================================================================
  164. sub warning {
  165. my $self = shift;
  166. CORE::warn("HTML::Parse: $_[0]\n") if $self->{'_warn'};
  167. # should maybe say HTML::TreeBuilder instead
  168. }
  169. #==========================================================================
  170. {
  171. # To avoid having to rebuild these lists constantly...
  172. my $_Closed_by_structurals = [qw(p h1 h2 h3 h4 h5 h6 pre textarea)];
  173. my $indent;
  174. sub start {
  175. return if $_[0]{'_stunted'};
  176. # Accept a signal from HTML::Parser for start-tags.
  177. my($self, $tag, $attr) = @_;
  178. # Parser passes more, actually:
  179. # $self->start($tag, $attr, $attrseq, $origtext)
  180. # But we can merrily ignore $attrseq and $origtext.
  181. if($tag eq 'x-html') {
  182. print "Ignoring open-x-html tag.\n" if DEBUG;
  183. # inserted by some lame code-generators.
  184. return; # bypass tweaking.
  185. }
  186. my $ptag = (
  187. my $pos = $self->{'_pos'} || $self
  188. )->{'_tag'};
  189. my $already_inserted;
  190. #my($indent);
  191. if(DEBUG) {
  192. # optimization -- don't figure out indenting unless we're in debug mode
  193. my @lineage = $pos->lineage;
  194. $indent = ' ' x (1 + @lineage);
  195. print
  196. $indent, "Proposing a new \U$tag\E under ",
  197. join('/', map $_->{'_tag'}, reverse($pos, @lineage)) || 'Root',
  198. ".\n";
  199. #} else {
  200. # $indent = ' ';
  201. }
  202. #print $indent, "POS: $pos ($ptag)\n" if DEBUG > 2;
  203. my $e =
  204. ($self->{'_element_class'} || 'HTML::Element')->new($tag, %$attr);
  205. # Make a new element object.
  206. # (Only rarely do we end up just throwing it away later in this call.)
  207. # Some prep -- custom messiness for those damned tables, and strict P's.
  208. if($self->{'_implicit_tags'}) { # wallawallawalla!
  209. unless($HTML::TreeBuilder::isTableElement{$tag}) {
  210. if ($ptag eq 'table') {
  211. print $indent,
  212. " * Phrasal \U$tag\E right under TABLE makes implicit TR and TD\n"
  213. if DEBUG > 1;
  214. $self->insert_element('tr', 1);
  215. $pos = $self->insert_element('td', 1); # yes, needs updating
  216. } elsif ($ptag eq 'tr') {
  217. print $indent,
  218. " * Phrasal \U$tag\E right under TR makes an implicit TD\n"
  219. if DEBUG > 1;
  220. $pos = $self->insert_element('td', 1); # yes, needs updating
  221. }
  222. $ptag = $pos->{'_tag'}; # yes, needs updating
  223. }
  224. # end of table-implication block.
  225. # Now maybe do a little dance to enforce P-strictness.
  226. # This seems like it should be integrated with the big
  227. # "ALL HOPE..." block, further below, but that doesn't
  228. # seem feasable.
  229. if(
  230. $self->{'_p_strict'}
  231. and $HTML::TreeBuilder::isKnown{$tag}
  232. and not $HTML::Tagset::is_Possible_Strict_P_Content{$tag}
  233. ) {
  234. my $here = $pos;
  235. my $here_tag = $ptag;
  236. while(1) {
  237. if($here_tag eq 'p') {
  238. print $indent,
  239. " * Inserting $tag closes strict P.\n" if DEBUG > 1;
  240. $self->end(\q{p});
  241. # NB: same as \'q', but less confusing to emacs cperl-mode
  242. last;
  243. }
  244. #print("Lasting from $here_tag\n"),
  245. last if
  246. $HTML::TreeBuilder::isKnown{$here_tag}
  247. and not $HTML::Tagset::is_Possible_Strict_P_Content{$here_tag};
  248. # Don't keep looking up the tree if we see something that can't
  249. # be strict-P content.
  250. $here_tag = ($here = $here->{'_parent'} || last)->{'_tag'};
  251. }# end while
  252. $ptag = ($pos = $self->{'_pos'} || $self)->{'_tag'}; # better update!
  253. }
  254. # end of strict-p block.
  255. }
  256. # And now, get busy...
  257. #----------------------------------------------------------------------
  258. if (!$self->{'_implicit_tags'}) { # bimskalabim
  259. # do nothing
  260. print $indent, " * _implicit_tags is off. doing nothing\n"
  261. if DEBUG > 1;
  262. #----------------------------------------------------------------------
  263. } elsif ($HTML::TreeBuilder::isHeadOrBodyElement{$tag}) {
  264. if ($pos->is_inside('body')) { # all is well
  265. print $indent,
  266. " * ambilocal element \U$tag\E is fine under BODY.\n"
  267. if DEBUG > 1;
  268. } elsif ($pos->is_inside('head')) {
  269. print $indent,
  270. " * ambilocal element \U$tag\E is fine under HEAD.\n"
  271. if DEBUG > 1;
  272. } else {
  273. # In neither head nor body! mmmmm... put under head?
  274. if ($ptag eq 'html') { # expected case
  275. # TODO?? : would there ever be a case where _head would be
  276. # absent from a tree that would ever be accessed at this
  277. # point?
  278. die "Where'd my head go?" unless ref $self->{'_head'};
  279. if ($self->{'_head'}{'_implicit'}) {
  280. print $indent,
  281. " * ambilocal element \U$tag\E makes an implicit HEAD.\n"
  282. if DEBUG > 1;
  283. # or rather, points us at it.
  284. $self->{'_pos'} = $self->{'_head'}; # to insert under...
  285. } else {
  286. $self->warning(
  287. "Ambilocal element <$tag> not under HEAD or BODY!?");
  288. # Put it under HEAD by default, I guess
  289. $self->{'_pos'} = $self->{'_head'}; # to insert under...
  290. }
  291. } else {
  292. # Neither under head nor body, nor right under html... pass thru?
  293. $self->warning(
  294. "Ambilocal element <$tag> neither under head nor body, nor right under html!?");
  295. }
  296. }
  297. #----------------------------------------------------------------------
  298. } elsif ($HTML::TreeBuilder::isBodyElement{$tag}) {
  299. # Ensure that we are within <body>
  300. if($ptag eq 'body') {
  301. # We're good.
  302. } elsif($HTML::TreeBuilder::isBodyElement{$ptag} # glarg
  303. and not $HTML::TreeBuilder::isHeadOrBodyElement{$ptag}
  304. ) {
  305. # Special case: Save ourselves a call to is_inside further down.
  306. # If our $ptag is an isBodyElement element (but not an
  307. # isHeadOrBodyElement element), then we must be under body!
  308. print $indent, " * Inferring that $ptag is under BODY.\n",
  309. if DEBUG > 3;
  310. # I think this and the test for 'body' trap everything
  311. # bodyworthy, except the case where the parent element is
  312. # under an unknown element that's a descendant of body.
  313. } elsif ($pos->is_inside('head')) {
  314. print $indent,
  315. " * body-element \U$tag\E minimizes HEAD, makes implicit BODY.\n"
  316. if DEBUG > 1;
  317. $ptag = (
  318. $pos = $self->{'_pos'} = $self->{'_body'} # yes, needs updating
  319. || die "Where'd my body go?"
  320. )->{'_tag'}; # yes, needs updating
  321. } elsif (! $pos->is_inside('body')) {
  322. print $indent,
  323. " * body-element \U$tag\E makes implicit BODY.\n"
  324. if DEBUG > 1;
  325. $ptag = (
  326. $pos = $self->{'_pos'} = $self->{'_body'} # yes, needs updating
  327. || die "Where'd my body go?"
  328. )->{'_tag'}; # yes, needs updating
  329. }
  330. # else we ARE under body, so okay.
  331. # Handle implicit endings and insert based on <tag> and position
  332. # ... ALL HOPE ABANDON ALL YE WHO ENTER HERE ...
  333. if ($tag eq 'p' or
  334. $tag eq 'h1' or $tag eq 'h2' or $tag eq 'h3' or
  335. $tag eq 'h4' or $tag eq 'h5' or $tag eq 'h6' or
  336. $tag eq 'form'
  337. # Hm, should <form> really be here?!
  338. ) {
  339. # Can't have <p>, <h#> or <form> inside these
  340. $self->end($_Closed_by_structurals,
  341. @HTML::TreeBuilder::p_closure_barriers
  342. # used to be just li!
  343. );
  344. } elsif ($tag eq 'ol' or $tag eq 'ul' or $tag eq 'dl') {
  345. # Can't have lists inside <h#> -- in the unlikely
  346. # event anyone tries to put them there!
  347. if (
  348. $ptag eq 'h1' or $ptag eq 'h2' or $ptag eq 'h3' or
  349. $ptag eq 'h4' or $ptag eq 'h5' or $ptag eq 'h6'
  350. ) {
  351. $self->end(\$ptag);
  352. }
  353. # TODO: Maybe keep closing up the tree until
  354. # the ptag isn't any of the above?
  355. # But anyone that says <h1><h2><ul>...
  356. # deserves what they get anyway.
  357. } elsif ($tag eq 'li') { # list item
  358. # Get under a list tag, one way or another
  359. unless(
  360. exists $HTML::TreeBuilder::isList{$ptag} or
  361. $self->end(\q{*}, keys %HTML::TreeBuilder::isList) #'
  362. ) {
  363. print $indent,
  364. " * inserting implicit UL for lack of containing ",
  365. join('|', keys %HTML::TreeBuilder::isList), ".\n"
  366. if DEBUG > 1;
  367. $self->insert_element('ul', 1);
  368. }
  369. } elsif ($tag eq 'dt' or $tag eq 'dd') {
  370. # Get under a DL, one way or another
  371. unless($ptag eq 'dl' or $self->end(\q{*}, 'dl')) { #'
  372. print $indent,
  373. " * inserting implicit DL for lack of containing DL.\n"
  374. if DEBUG > 1;
  375. $self->insert_element('dl', 1);
  376. }
  377. } elsif ($HTML::TreeBuilder::isFormElement{$tag}) {
  378. if($self->{'_ignore_formies_outside_form'} # TODO: document this
  379. and not $pos->is_inside('form')
  380. ) {
  381. print $indent,
  382. " * ignoring \U$tag\E because not in a FORM.\n"
  383. if DEBUG > 1;
  384. return; # bypass tweaking.
  385. }
  386. if($tag eq 'option') {
  387. # return unless $ptag eq 'select';
  388. $self->end(\q{option});
  389. $ptag = ($self->{'_pos'} || $self)->{'_tag'};
  390. unless($ptag eq 'select' or $ptag eq 'optgroup') {
  391. print $indent, " * \U$tag\E makes an implicit SELECT.\n"
  392. if DEBUG > 1;
  393. $pos = $self->insert_element('select', 1);
  394. # but not a very useful select -- has no 'name' attribute!
  395. # is $pos's value used after this?
  396. }
  397. }
  398. } elsif ($HTML::TreeBuilder::isTableElement{$tag}) {
  399. if($tag eq 'td' or $tag eq 'th') {
  400. # Get under a tr one way or another
  401. unless(
  402. $ptag eq 'tr' # either under a tr
  403. or $self->end(\q{*}, 'tr', 'table') #or we can get under one
  404. ) {
  405. print $indent,
  406. " * \U$tag\E under \U$ptag\E makes an implicit TR\n"
  407. if DEBUG > 1;
  408. $self->insert_element('tr', 1);
  409. # presumably pos's value isn't used after this.
  410. }
  411. } else {
  412. $self->end(\$tag, 'table'); #'
  413. }
  414. # Hmm, I guess this is right. To work it out:
  415. # tr closes any open tr (limited at a table)
  416. # thead closes any open thead (limited at a table)
  417. # tbody closes any open tbody (limited at a table)
  418. # tfoot closes any open tfoot (limited at a table)
  419. # colgroup closes any open colgroup (limited at a table)
  420. # col can try, but will always fail, at the enclosing table,
  421. # as col is empty, and therefore never open!
  422. # But!
  423. # td closes any open td OR th (limited at a table)
  424. # th closes any open th OR td (limited at a table)
  425. # ...implementable as "close to a tr, or make a tr"
  426. if(!$pos->is_inside('table')) {
  427. print $indent, " * \U$tag\E makes an implicit TABLE\n"
  428. if DEBUG > 1;
  429. $self->insert_element('table', 1);
  430. }
  431. } elsif ($HTML::TreeBuilder::isPhraseMarkup{$tag}) {
  432. if($ptag eq 'body' and $self->{'_implicit_body_p_tag'}) {
  433. print
  434. " * Phrasal \U$tag\E right under BODY makes an implicit P\n"
  435. if DEBUG > 1;
  436. $pos = $self->insert_element('p', 1);
  437. # is $pos's value used after this?
  438. }
  439. }
  440. # End of implicit endings logic
  441. # End of "elsif ($HTML::TreeBuilder::isBodyElement{$tag}"
  442. #----------------------------------------------------------------------
  443. } elsif ($HTML::TreeBuilder::isHeadElement{$tag}) {
  444. if ($pos->is_inside('body')) {
  445. print $indent, " * head element \U$tag\E found inside BODY!\n"
  446. if DEBUG;
  447. $self->warning("Header element <$tag> in body"); # [sic]
  448. } elsif (!$pos->is_inside('head')) {
  449. print $indent, " * head element \U$tag\E makes an implicit HEAD.\n"
  450. if DEBUG > 1;
  451. } else {
  452. print $indent,
  453. " * head element \U$tag\E goes inside existing HEAD.\n"
  454. if DEBUG > 1;
  455. }
  456. $self->{'_pos'} = $self->{'_head'} || die "Where'd my head go?";
  457. #----------------------------------------------------------------------
  458. } elsif ($tag eq 'html') {
  459. if(delete $self->{'_implicit'}) { # first time here
  460. print $indent, " * good! found the real HTML element!\n"
  461. if DEBUG > 1;
  462. } else {
  463. print $indent, " * Found a second HTML element\n"
  464. if DEBUG;
  465. $self->warning("Found a nested <html> element");
  466. }
  467. # in either case, migrate attributes to the real element
  468. for (keys %$attr) {
  469. $self->attr($_, $attr->{$_});
  470. }
  471. $self->{'_pos'} = undef;
  472. return $self; # bypass tweaking.
  473. #----------------------------------------------------------------------
  474. } elsif ($tag eq 'head') {
  475. my $head = $self->{'_head'} || die "Where'd my head go?";
  476. if(delete $head->{'_implicit'}) { # first time here
  477. print $indent, " * good! found the real HEAD element!\n"
  478. if DEBUG > 1;
  479. } else { # been here before
  480. print $indent, " * Found a second HEAD element\n"
  481. if DEBUG;
  482. $self->warning("Found a second <head> element");
  483. }
  484. # in either case, migrate attributes to the real element
  485. for (keys %$attr) {
  486. $head->attr($_, $attr->{$_});
  487. }
  488. return $self->{'_pos'} = $head; # bypass tweaking.
  489. #----------------------------------------------------------------------
  490. } elsif ($tag eq 'body') {
  491. my $body = $self->{'_body'} || die "Where'd my body go?";
  492. if(delete $body->{'_implicit'}) { # first time here
  493. print $indent, " * good! found the real BODY element!\n"
  494. if DEBUG > 1;
  495. } else { # been here before
  496. print $indent, " * Found a second BODY element\n"
  497. if DEBUG;
  498. $self->warning("Found a second <body> element");
  499. }
  500. # in either case, migrate attributes to the real element
  501. for (keys %$attr) {
  502. $body->attr($_, $attr->{$_});
  503. }
  504. return $self->{'_pos'} = $body; # bypass tweaking.
  505. #----------------------------------------------------------------------
  506. } elsif ($tag eq 'frameset') {
  507. if(
  508. !($self->{'_frameset_seen'}++) # first frameset seen
  509. and !$self->{'_noframes_seen'}
  510. # otherwise it'll be under the noframes already
  511. and !$self->is_inside('body')
  512. ) {
  513. # The following is a bit of a hack. We don't use the normal
  514. # insert_element because 1) we don't want it as _pos, but instead
  515. # right under $self, and 2), more importantly, that we don't want
  516. # this inserted at the /end/ of $self's content_list, but instead
  517. # in the middle of it, specifiaclly right before the body element.
  518. #
  519. my $c = $self->{'_content'} || die "Contentless root?";
  520. my $body = $self->{'_body'} || die "Where'd my BODY go?";
  521. for(my $i = 0; $i < @$c; ++$i) {
  522. if($c->[$i] eq $body) {
  523. splice(@$c, $i, 0, $self->{'_pos'} = $pos = $e);
  524. $e->{'_parent'} = $self;
  525. $already_inserted = 1;
  526. print $indent, " * inserting 'frameset' right before BODY.\n"
  527. if DEBUG > 1;
  528. last;
  529. }
  530. }
  531. die "BODY not found in children of root?" unless $already_inserted;
  532. }
  533. } elsif ($tag eq 'frame') {
  534. # Okay, fine, pass thru.
  535. # Should probably enforce that these should be under a frameset.
  536. # But hey. Ditto for enforcing that 'noframes' should be under
  537. # a 'frameset', as the DTDs say.
  538. } elsif ($tag eq 'noframes') {
  539. # This basically assumes there'll be exactly one 'noframes' element
  540. # per document. At least, only the first one gets to have the
  541. # body under it. And if there are no noframes elements, then
  542. # the body pretty much stays where it is. Is that ever a problem?
  543. if($self->{'_noframes_seen'}++) {
  544. print $indent, " * ANOTHER noframes element?\n" if DEBUG;
  545. } else {
  546. if($pos->is_inside('body')) {
  547. print $indent, " * 'noframes' inside 'body'. Odd!\n" if DEBUG;
  548. # In that odd case, we /can't/ make body a child of 'noframes',
  549. # because it's an ancestor of the 'noframes'!
  550. } else {
  551. $e->push_content( $self->{'_body'} || die "Where'd my body go?" );
  552. print $indent, " * Moving body to be under noframes.\n" if DEBUG;
  553. }
  554. }
  555. #----------------------------------------------------------------------
  556. } else {
  557. # unknown tag
  558. if ($self->{'_ignore_unknown'}) {
  559. print $indent, " * Ignoring unknown tag \U$tag\E\n" if DEBUG;
  560. $self->warning("Skipping unknown tag $tag");
  561. return;
  562. } else {
  563. print $indent, " * Accepting unknown tag \U$tag\E\n"
  564. if DEBUG;
  565. }
  566. }
  567. #----------------------------------------------------------------------
  568. # End of mumbo-jumbo
  569. print
  570. $indent, "(Attaching ", $e->{'_tag'}, " under ",
  571. ($self->{'_pos'} || $self)->{'_tag'}, ")\n"
  572. # because if _pos isn't defined, it goes under self
  573. if DEBUG;
  574. # The following if-clause is to delete /some/ ignorable whitespace
  575. # nodes, as we're making the tree.
  576. # This'd be a node we'd catch later anyway, but we might as well
  577. # nip it in the bud now.
  578. # This doesn't catch /all/ deletable WS-nodes, so we do have to call
  579. # the tightener later to catch the rest.
  580. if($self->{'_tighten'} and !$self->{'_ignore_text'}) { # if tightenable
  581. my($sibs, $par);
  582. if(
  583. ($sibs = ( $par = $self->{'_pos'} || $self )->{'_content'})
  584. and @$sibs # parent already has content
  585. and !ref($sibs->[-1]) # and the last one there is a text node
  586. and $sibs->[-1] !~ m<\S>s # and it's all whitespace
  587. and ( # one of these has to be eligible...
  588. $HTML::TreeBuilder::canTighten{$tag}
  589. or
  590. (
  591. (@$sibs == 1)
  592. ? # WS is leftmost -- so parent matters
  593. $HTML::TreeBuilder::canTighten{$par->{'_tag'}}
  594. : # WS is after another node -- it matters
  595. (ref $sibs->[-2]
  596. and $HTML::TreeBuilder::canTighten{$sibs->[-2]{'_tag'}}
  597. )
  598. )
  599. )
  600. and !$par->is_inside('pre', 'xmp', 'textarea', 'plaintext')
  601. # we're clear
  602. ) {
  603. pop @$sibs;
  604. print $indent, "Popping a preceding all-WS node\n" if DEBUG;
  605. }
  606. }
  607. $self->insert_element($e) unless $already_inserted;
  608. if(DEBUG) {
  609. if($self->{'_pos'}) {
  610. print
  611. $indent, "(Current lineage of pos: \U$tag\E under ",
  612. join('/',
  613. reverse(
  614. # $self->{'_pos'}{'_tag'}, # don't list myself!
  615. $self->{'_pos'}->lineage_tag_names
  616. )
  617. ),
  618. ".)\n";
  619. } else {
  620. print $indent, "(Pos points nowhere!?)\n";
  621. }
  622. }
  623. unless(($self->{'_pos'} || '') eq $e) {
  624. # if it's an empty element -- i.e., if it didn't change the _pos
  625. &{ $self->{"_tweak_$tag"}
  626. || $self->{'_tweak_*'}
  627. || return $e
  628. }(map $_, $e, $tag, $self); # make a list so the user can't clobber
  629. }
  630. return $e;
  631. }
  632. }
  633. #==========================================================================
  634. {
  635. my $indent;
  636. sub end {
  637. return if $_[0]{'_stunted'};
  638. # Either: Acccept an end-tag signal from HTML::Parser
  639. # Or: Method for closing currently open elements in some fairly complex
  640. # way, as used by other methods in this class.
  641. my($self, $tag, @stop) = @_;
  642. if($tag eq 'x-html') {
  643. print "Ignoring close-x-html tag.\n" if DEBUG;
  644. # inserted by some lame code-generators.
  645. return;
  646. }
  647. # This method accepts two calling formats:
  648. # 1) from Parser: $self->end('tag_name', 'origtext')
  649. # in which case we shouldn't mistake origtext as a blocker tag
  650. # 2) from myself: $self->end(\q{tagname1}, 'blk1', ... )
  651. # from myself: $self->end(['tagname1', 'tagname2'], 'blk1', ... )
  652. # End the specified tag, but don't move above any of the blocker tags.
  653. # The tag can also be a reference to an array. Terminate the first
  654. # tag found.
  655. my $ptag = ( my $p = $self->{'_pos'} || $self )->{'_tag'};
  656. # $p and $ptag are sort-of stratch
  657. if(ref($tag)) {
  658. # First param is a ref of one sort or another --
  659. # THE CALL IS COMING FROM INSIDE THE HOUSE!
  660. $tag = $$tag if ref($tag) eq 'SCALAR';
  661. # otherwise it's an arrayref.
  662. } else {
  663. # the call came from Parser -- just ignore origtext
  664. @stop = ();
  665. }
  666. #my($indent);
  667. if(DEBUG) {
  668. # optimization -- don't figure out depth unless we're in debug mode
  669. my @lineage_tags = $p->lineage_tag_names;
  670. $indent = ' ' x (1 + @lineage_tags);
  671. # now announce ourselves
  672. print $indent, "Ending ",
  673. ref($tag) ? ('[', join(' ', @$tag ), ']') : "\U$tag\E",
  674. scalar(@stop) ? (" no higher than [", join(' ', @stop), "]" )
  675. : (), ".\n"
  676. ;
  677. print $indent, " (Current lineage: ", join('/', @lineage_tags), ".)\n"
  678. if DEBUG > 1;
  679. if(DEBUG > 3) {
  680. #my(
  681. # $package, $filename, $line, $subroutine,
  682. # $hasargs, $wantarray, $evaltext, $is_require) = caller;
  683. print $indent,
  684. " (Called from ", (caller(1))[3], ' line ', (caller(1))[2],
  685. ")\n";
  686. }
  687. #} else {
  688. # $indent = ' ';
  689. }
  690. # End of if DEBUG
  691. # Now actually do it
  692. my @to_close;
  693. if($tag eq '*') {
  694. # Special -- close everything up to (but not including) the first
  695. # limiting tag, or return if none found. Somewhat of a special case.
  696. PARENT:
  697. while (defined $p) {
  698. $ptag = $p->{'_tag'};
  699. print $indent, " (Looking at $ptag.)\n" if DEBUG > 2;
  700. for (@stop) {
  701. if($ptag eq $_) {
  702. print $indent, " (Hit a $_; closing everything up to here.)\n"
  703. if DEBUG > 2;
  704. last PARENT;
  705. }
  706. }
  707. push @to_close, $p;
  708. $p = $p->{'_parent'}; # no match so far? keep moving up
  709. print
  710. $indent,
  711. " (Moving on up to ", $p ? $p->{'_tag'} : 'nil', ")\n"
  712. if DEBUG > 1;
  713. ;
  714. }
  715. unless(defined $p) { # We never found what we were looking for.
  716. print $indent, " (We never found a limit.)\n" if DEBUG > 1;
  717. return;
  718. }
  719. #print
  720. # $indent,
  721. # " (To close: ", join('/', map $_->tag, @to_close), ".)\n"
  722. # if DEBUG > 4;
  723. # Otherwise update pos and fall thru.
  724. $self->{'_pos'} = $p;
  725. } elsif (ref $tag) {
  726. # Close the first of any of the matching tags, giving up if you hit
  727. # any of the stop-tags.
  728. PARENT:
  729. while (defined $p) {
  730. $ptag = $p->{'_tag'};
  731. print $indent, " (Looking at $ptag.)\n" if DEBUG > 2;
  732. for (@$tag) {
  733. if($ptag eq $_) {
  734. print $indent, " (Closing $_.)\n" if DEBUG > 2;
  735. last PARENT;
  736. }
  737. }
  738. for (@stop) {
  739. if($ptag eq $_) {
  740. print $indent, " (Hit a limiting $_ -- bailing out.)\n"
  741. if DEBUG > 1;
  742. return; # so it was all for naught
  743. }
  744. }
  745. push @to_close, $p;
  746. $p = $p->{'_parent'};
  747. }
  748. return unless defined $p; # We went off the top of the tree.
  749. # Otherwise specified element was found; set pos to its parent.
  750. push @to_close, $p;
  751. $self->{'_pos'} = $p->{'_parent'};
  752. } else {
  753. # Close the first of the specified tag, giving up if you hit
  754. # any of the stop-tags.
  755. while (defined $p) {
  756. $ptag = $p->{'_tag'};
  757. print $indent, " (Looking at $ptag.)\n" if DEBUG > 2;
  758. if($ptag eq $tag) {
  759. print $indent, " (Closing $tag.)\n" if DEBUG > 2;
  760. last;
  761. }
  762. for (@stop) {
  763. if($ptag eq $_) {
  764. print $indent, " (Hit a limiting $_ -- bailing out.)\n"
  765. if DEBUG > 1;
  766. return; # so it was all for naught
  767. }
  768. }
  769. push @to_close, $p;
  770. $p = $p->{'_parent'};
  771. }
  772. return unless defined $p; # We went off the top of the tree.
  773. # Otherwise specified element was found; set pos to its parent.
  774. push @to_close, $p;
  775. $self->{'_pos'} = $p->{'_parent'};
  776. }
  777. $self->{'_pos'} = undef if $self eq ($self->{'_pos'} || '');
  778. print $indent, "(Pos now points to ",
  779. $self->{'_pos'} ? $self->{'_pos'}{'_tag'} : '???', ".)\n"
  780. if DEBUG > 1;
  781. ### EXPENSIVE, because has to check that it's not under a pre
  782. ### or a CDATA-parent. That's one more method call per end()!
  783. ### Might as well just do this at the end of the tree-parse, I guess,
  784. ### at which point we'd be parsing top-down, and just not traversing
  785. ### under pre's or CDATA-parents.
  786. ##
  787. ## Take this opportunity to nix any terminal whitespace nodes.
  788. ## TODO: consider whether this (plus the logic in start(), above)
  789. ## would ever leave any WS nodes in the tree.
  790. ## If not, then there's no reason to have eof() call
  791. ## delete_ignorable_whitespace on the tree, is there?
  792. ##
  793. #if(@to_close and $self->{'_tighten'} and !$self->{'_ignore_text'} and
  794. # ! $to_close[-1]->is_inside('pre', keys %HTML::Tagset::isCDATA_Parent)
  795. #) { # if tightenable
  796. # my($children, $e_tag);
  797. # foreach my $e (reverse @to_close) { # going top-down
  798. # last if 'pre' eq ($e_tag = $e->{'_tag'}) or
  799. # $HTML::Tagset::isCDATA_Parent{$e_tag};
  800. #
  801. # if(
  802. # $children = $e->{'_content'}
  803. # and @$children # has children
  804. # and !ref($children->[-1])
  805. # and $children->[-1] =~ m<^\s+$>s # last node is all-WS
  806. # and
  807. # (
  808. # # has a tightable parent:
  809. # $HTML::TreeBuilder::canTighten{ $e_tag }
  810. # or
  811. # ( # has a tightenable left sibling:
  812. # @$children > 1 and
  813. # ref($children->[-2])
  814. # and $HTML::TreeBuilder::canTighten{ $children->[-2]{'_tag'} }
  815. # )
  816. # )
  817. # ) {
  818. # pop @$children;
  819. # #print $indent, "Popping a terminal WS node from ", $e->{'_tag'},
  820. # # " (", $e->address, ") while exiting.\n" if DEBUG;
  821. # }
  822. # }
  823. #}
  824. foreach my $e (@to_close) {
  825. # Call the applicable callback, if any
  826. $ptag = $e->{'_tag'};
  827. &{ $self->{"_tweak_$ptag"}
  828. || $self->{'_tweak_*'}
  829. || next
  830. }(map $_, $e, $ptag, $self);
  831. print $indent, "Back from tweaking.\n" if DEBUG;
  832. last if $self->{'_stunted'}; # in case one of the handlers called stunt
  833. }
  834. return @to_close;
  835. }
  836. }
  837. #==========================================================================
  838. {
  839. my($indent, $nugget);
  840. sub text {
  841. return if $_[0]{'_stunted'};
  842. # Accept a "here's a text token" signal from HTML::Parser.
  843. my($self, $text, $is_cdata) = @_;
  844. # the >3.0 versions of Parser may pass a cdata node.
  845. # Thanks to Gisle Aas for pointing this out.
  846. return unless length $text; # I guess that's always right
  847. my $ignore_text = $self->{'_ignore_text'};
  848. my $no_space_compacting = $self->{'_no_space_compacting'};
  849. my $pos = $self->{'_pos'} || $self;
  850. HTML::Entities::decode($text)
  851. unless $ignore_text || $is_cdata
  852. || $HTML::Tagset::isCDATA_Parent{$pos->{'_tag'}};
  853. #my($indent, $nugget);
  854. if(DEBUG) {
  855. # optimization -- don't figure out depth unless we're in debug mode
  856. my @lineage_tags = $pos->lineage_tag_names;
  857. $indent = ' ' x (1 + @lineage_tags);
  858. $nugget = (length($text) <= 25) ? $text : (substr($text,0,25) . '...');
  859. $nugget =~ s<([\x00-\x1F])>
  860. <'\\x'.(unpack("H2",$1))>eg;
  861. print
  862. $indent, "Proposing a new text node ($nugget) under ",
  863. join('/', reverse($pos->{'_tag'}, @lineage_tags)) || 'Root',
  864. ".\n";
  865. #} else {
  866. # $indent = ' ';
  867. }
  868. my $ptag;
  869. if ($HTML::Tagset::isCDATA_Parent{$ptag = $pos->{'_tag'}}
  870. #or $pos->is_inside('pre')
  871. or $pos->is_inside('pre', 'textarea')
  872. ) {
  873. return if $ignore_text;
  874. $pos->push_content($text);
  875. } else {
  876. # return unless $text =~ /\S/; # This is sometimes wrong
  877. if (!$self->{'_implicit_tags'} || $text !~ /\S/) {
  878. # don't change anything
  879. } elsif ($ptag eq 'head' or $ptag eq 'noframes') {
  880. if($self->{'_implicit_body_p_tag'}) {
  881. print $indent,
  882. " * Text node under \U$ptag\E closes \U$ptag\E, implicates BODY and P.\n"
  883. if DEBUG > 1;
  884. $self->end(\$ptag);
  885. $pos =
  886. $self->{'_body'}
  887. ? ($self->{'_pos'} = $self->{'_body'}) # expected case
  888. : $self->insert_element('body', 1);
  889. $pos = $self->insert_element('p', 1);
  890. } else {
  891. print $indent,
  892. " * Text node under \U$ptag\E closes, implicates BODY.\n"
  893. if DEBUG > 1;
  894. $self->end(\$ptag);
  895. $pos =
  896. $self->{'_body'}
  897. ? ($self->{'_pos'} = $self->{'_body'}) # expected case
  898. : $self->insert_element('body', 1);
  899. }
  900. } elsif ($ptag eq 'html') {
  901. if($self->{'_implicit_body_p_tag'}) {
  902. print $indent,
  903. " * Text node under HTML implicates BODY and P.\n"
  904. if DEBUG > 1;
  905. $pos =
  906. $self->{'_body'}
  907. ? ($self->{'_pos'} = $self->{'_body'}) # expected case
  908. : $self->insert_element('body', 1);
  909. $pos = $self->insert_element('p', 1);
  910. } else {
  911. print $indent,
  912. " * Text node under HTML implicates BODY.\n"
  913. if DEBUG > 1;
  914. $pos =
  915. $self->{'_body'}
  916. ? ($self->{'_pos'} = $self->{'_body'}) # expected case
  917. : $self->insert_element('body', 1);
  918. #print "POS is $pos, ", $pos->{'_tag'}, "\n";
  919. }
  920. } elsif ($ptag eq 'body') {
  921. if($self->{'_implicit_body_p_tag'}) {
  922. print $indent,
  923. " * Text node under BODY implicates P.\n"
  924. if DEBUG > 1;
  925. $pos = $self->insert_element('p', 1);
  926. }
  927. } elsif ($ptag eq 'table') {
  928. print $indent,
  929. " * Text node under TABLE implicates TR and TD.\n"
  930. if DEBUG > 1;
  931. $self->insert_element('tr', 1);
  932. $pos = $self->insert_element('td', 1);
  933. # double whammy!
  934. } elsif ($ptag eq 'tr') {
  935. print $indent,
  936. " * Text node under TR implicates TD.\n"
  937. if DEBUG > 1;
  938. $pos = $self->insert_element('td', 1);
  939. }
  940. # elsif (
  941. # # $ptag eq 'li' ||
  942. # # $ptag eq 'dd' ||
  943. # $ptag eq 'form') {
  944. # $pos = $self->insert_element('p', 1);
  945. #}
  946. # Whatever we've done above should have had the side
  947. # effect of updating $self->{'_pos'}
  948. #print "POS is now $pos, ", $pos->{'_tag'}, "\n";
  949. return if $ignore_text;
  950. $text =~ s/\s+/ /g unless $no_space_compacting ; # canonical space
  951. print
  952. $indent, " (Attaching text node ($nugget) under ",
  953. # was: $self->{'_pos'} ? $self->{'_pos'}{'_tag'} : $self->{'_tag'},
  954. $pos->{'_tag'},
  955. ").\n"
  956. if DEBUG > 1;
  957. $pos->push_content($text);
  958. }
  959. &{ $self->{'_tweak_~text'} || return }($text, $pos, $pos->{'_tag'} . '');
  960. # Note that this is very exceptional -- it doesn't fall back to
  961. # _tweak_*, and it gives its tweak different arguments.
  962. return;
  963. }
  964. }
  965. #==========================================================================
  966. # TODO: test whether comment(), declaration(), and process(), do the right
  967. # thing as far as tightening and whatnot.
  968. # Also, currently, doctypes and comments that appear before head or body
  969. # show up in the tree in the wrong place. Something should be done about
  970. # this. Tricky. Maybe this whole business of pre-making the body and
  971. # whatnot is wrong.
  972. sub comment {
  973. return if $_[0]{'_stunted'};
  974. # Accept a "here's a comment" signal from HTML::Parser.
  975. my($self, $text) = @_;
  976. my $pos = $self->{'_pos'} || $self;
  977. return unless $self->{'_store_comments'}
  978. || $HTML::Tagset::isCDATA_Parent{ $pos->{'_tag'} };
  979. if(DEBUG) {
  980. my @lineage_tags = $pos->lineage_tag_names;
  981. my $indent = ' ' x (1 + @lineage_tags);
  982. my $nugget = (length($text) <= 25) ? $text : (substr($text,0,25) . '...');
  983. $nugget =~ s<([\x00-\x1F])>
  984. <'\\x'.(unpack("H2",$1))>eg;
  985. print
  986. $indent, "Proposing a Comment ($nugget) under ",
  987. join('/', reverse($pos->{'_tag'}, @lineage_tags)) || 'Root',
  988. ".\n";
  989. }
  990. (my $e = (
  991. $self->{'_element_class'} || 'HTML::Element'
  992. )->new('~comment'))->{'text'} = $text;
  993. $pos->push_content($e);
  994. ++($self->{'_element_count'});
  995. &{ $self->{'_tweak_~comment'}
  996. || $self->{'_tweak_*'}
  997. || return $e
  998. }(map $_, $e, '~comment', $self);
  999. return $e;
  1000. }
  1001. #==========================================================================
  1002. # TODO: currently this puts declarations in just the wrong place.
  1003. # How to correct? look at pos->_content, and go to insert at end,
  1004. # but back up before any head elements? Do that just if implicit
  1005. # mode is on?
  1006. sub declaration {
  1007. return if $_[0]{'_stunted'};
  1008. # Accept a "here's a markup declaration" signal from HTML::Parser.
  1009. return unless $_[0]->{'_store_declarations'};
  1010. my($self, $text) = @_;
  1011. my $pos = $self->{'_pos'} || $self;
  1012. if(DEBUG) {
  1013. my @lineage_tags = $pos->lineage_tag_names;
  1014. my $indent = ' ' x (1 + @lineage_tags);
  1015. my $nugget = (length($text) <= 25) ? $text : (substr($text,0,25) . '...');
  1016. $nugget =~ s<([\x00-\x1F])>
  1017. <'\\x'.(unpack("H2",$1))>eg;
  1018. print
  1019. $indent, "Proposing a Declaration ($nugget) under ",
  1020. join('/', reverse($pos->{'_tag'}, @lineage_tags)) || 'Root',
  1021. ".\n";
  1022. }
  1023. (my $e = (
  1024. $self->{'_element_class'} || 'HTML::Element'
  1025. )->new('~declaration'))->{'text'} = $text;
  1026. $pos->push_content($e);
  1027. ++($self->{'_element_count'});
  1028. &{ $self->{'_tweak_~declaration'}
  1029. || $self->{'_tweak_*'}
  1030. || return $e
  1031. }(map $_, $e, '~declaration', $self);
  1032. return $e;
  1033. }
  1034. #==========================================================================
  1035. sub process {
  1036. return if $_[0]{'_stunted'};
  1037. # Accept a "here's a PI" signal from HTML::Parser.
  1038. return unless $_[0]->{'_store_pis'};
  1039. my($self, $text) = @_;
  1040. my $pos = $self->{'_pos'} || $self;
  1041. if(DEBUG) {
  1042. my @lineage_tags = $pos->lineage_tag_names;
  1043. my $indent = ' ' x (1 + @lineage_tags);
  1044. my $nugget = (length($text) <= 25) ? $text : (substr($text,0,25) . '...');
  1045. $nugget =~ s<([\x00-\x1F])>
  1046. <'\\x'.(unpack("H2",$1))>eg;
  1047. print
  1048. $indent, "Proposing a PI ($nugget) under ",
  1049. join('/', reverse($pos->{'_tag'}, @lineage_tags)) || 'Root',
  1050. ".\n";
  1051. }
  1052. (my $e = (
  1053. $self->{'_element_class'} || 'HTML::Element'
  1054. )->new('~pi'))->{'text'} = $text;
  1055. $pos->push_content($e);
  1056. ++($self->{'_element_count'});
  1057. &{ $self->{'_tweak_~pi'}
  1058. || $self->{'_tweak_*'}
  1059. || return $e
  1060. }(map $_, $e, '~pi', $self);
  1061. return $e;
  1062. }
  1063. #==========================================================================
  1064. #When you call $tree->parse_file($filename), and the
  1065. #tree's ignore_ignorable_whitespace attribute is on (as it is
  1066. #by default), HTML::TreeBuilder's logic will manage to avoid
  1067. #creating some, but not all, nodes that represent ignorable
  1068. #whitespace. However, at the end of its parse, it traverses the
  1069. #tree and deletes any that it missed. (It does this with an
  1070. #around-method around HTML::Parser's eof method.)
  1071. #
  1072. #However, with $tree->parse($content), the cleanup-traversal step
  1073. #doesn't happen automatically -- so when you're done parsing all
  1074. #content for a document (regardless of whether $content is the only
  1075. #bit, or whether it's just another chunk of content you're parsing into
  1076. #the tree), call $tree->eof() to signal that you're at the end of the
  1077. #text you're inputting to the tree. Besides properly cleaning any bits
  1078. #of ignorable whitespace from the tree, this will also ensure that
  1079. #HTML::Parser's internal buffer is flushed.
  1080. sub eof {
  1081. # Accept an "end-of-file" signal from HTML::Parser, or thrown by the user.
  1082. return $_[0]->SUPER::eof() if $_[0]->{'_stunted'};
  1083. my $x = $_[0];
  1084. print "EOF received.\n" if DEBUG;
  1085. my(@rv);
  1086. if(wantarray) {
  1087. # I don't think this makes any difference for this particular
  1088. # method, but let's be scrupulous, for once.
  1089. @rv = $x->SUPER::eof();
  1090. } else {
  1091. $rv[0] = $x->SUPER::eof();
  1092. }
  1093. $x->end('html') unless $x eq ($x->{'_pos'} || $x);
  1094. # That SHOULD close everything, and will run the appropriate tweaks.
  1095. # We /could/ be running under some insane mode such that there's more
  1096. # than one HTML element, but really, that's just insane to do anyhow.
  1097. unless($x->{'_implicit_tags'}) {
  1098. # delete those silly implicit head and body in case we put
  1099. # them there in implicit tags mode
  1100. foreach my $node ($x->{'_head'}, $x->{'_body'}) {
  1101. $node->replace_with_content
  1102. if defined $node and ref $node
  1103. and $node->{'_implicit'} and $node->{'_parent'};
  1104. # I think they should be empty anyhow, since the only
  1105. # logic that'd insert under them can apply only, I think,
  1106. # in the case where _implicit_tags is on
  1107. }
  1108. # this may still leave an implicit 'html' at the top, but there's
  1109. # nothing we can do about that, is there?
  1110. }
  1111. $x->delete_ignorable_whitespace()
  1112. # this's why we trap this -- an after-method
  1113. if $x->{'_tighten'} and ! $x->{'_ignore_text'};
  1114. return @rv if wantarray;
  1115. return $rv[0];
  1116. }
  1117. #==========================================================================
  1118. # TODO: document
  1119. sub stunt {
  1120. my $self = $_[0];
  1121. print "Stunting the tree.\n" if DEBUG;
  1122. if($HTML::Parser::VERSION < 3) {
  1123. #This is a MEAN MEAN HACK. And it works most of the time!
  1124. $self->{'_buf'} = '';
  1125. my $fh = *HTML::Parser::F{IO};
  1126. # the local'd FH used by parse_file loop
  1127. if(defined $fh) {
  1128. print "Closing Parser's filehandle $fh\n" if DEBUG;
  1129. close($fh);
  1130. }
  1131. # But if they called $tree->parse_file($filehandle)
  1132. # or $tree->parse_file(*IO), then there will be no *HTML::Parser::F{IO}
  1133. # to close. Ahwell. Not a problem for most users these days.
  1134. } else {
  1135. $self->SUPER::eof();
  1136. # Under 3+ versions, calling eof from inside a parse will abort the
  1137. # parse / parse_file
  1138. }
  1139. # In the off chance that the above didn't work, we'll throw
  1140. # this flag to make any future events be no-ops.
  1141. $self->stunted(1);
  1142. return;
  1143. }
  1144. # TODO: document
  1145. sub stunted { shift->_elem('_stunted', @_); }
  1146. #==========================================================================
  1147. sub delete {
  1148. # Override Element's delete method.
  1149. # This does most, if not all, of what Element's delete does anyway.
  1150. # Deletes content, including content in some special attributes.
  1151. # But doesn't empty out the hash.
  1152. $_[0]->{'_element_count'} = 1; # never hurts to be scrupulously correct
  1153. delete @{$_[0]}{'_body', '_head', '_pos'};
  1154. for (@{ delete($_[0]->{'_content'})
  1155. || []
  1156. }, # all/any content
  1157. # delete @{$_[0]}{'_body', '_head', '_pos'}
  1158. # ...and these, in case these elements don't appear in the
  1159. # content, which is possible. If they did appear (as they
  1160. # usually do), then calling $_->delete on them again is harmless.
  1161. # I don't think that's such a hot idea now. Thru creative reattachment,
  1162. # those could actually now point to elements in OTHER trees (which we do
  1163. # NOT want to delete!).
  1164. ## Reasoned out:
  1165. # If these point to elements not in the content list of any element in this
  1166. # tree, but not in the content list of any element in any OTHER tree, then
  1167. # just deleting these will make their refcounts hit zero.
  1168. # If these point to elements in the content lists of elements in THIS tree,
  1169. # then we'll get to deleting them when we delete from the top.
  1170. # If these point to elements in the content lists of elements in SOME OTHER
  1171. # tree, then they're not to be deleted.
  1172. )
  1173. {
  1174. $_->delete
  1175. if defined $_ and ref $_ # Make sure it's an object.
  1176. and $_ ne $_[0]; # And avoid hitting myself, just in case!
  1177. }
  1178. return undef;
  1179. }
  1180. sub tighten_up { # legacy
  1181. shift->delete_ignorable_whitespace(@_);
  1182. }
  1183. sub elementify {
  1184. # Rebless this object down into the normal element class.
  1185. my $self = $_[0];
  1186. my $to_class = ($self->{'_element_class'} || 'HTML::Element');
  1187. delete @{$self}{ grep {;
  1188. length $_ and substr($_,0,1) eq '_'
  1189. # The private attributes that we'll retain:
  1190. and $_ ne '_tag' and $_ ne '_parent' and $_ ne '_content'
  1191. and $_ ne '_implicit' and $_ ne '_pos'
  1192. and $_ ne '_element_class'
  1193. } keys %$self };
  1194. bless $self, $to_class; # Returns the same object we were fed
  1195. }
  1196. #--------------------------------------------------------------------------
  1197. 1;
  1198. __END__
  1199. =head1 NAME
  1200. HTML::TreeBuilder - Parser that builds a HTML syntax tree
  1201. =head1 SYNOPSIS
  1202. foreach my $file_name (@ARGV) {
  1203. my $tree = HTML::TreeBuilder->new; # empty tree
  1204. $tree->parse_file($file_name);
  1205. print "Hey, here's a dump of the parse tree of $file_name:\n";
  1206. $tree->dump; # a method we inherit from HTML::Element
  1207. print "And here it is, bizarrely rerendered as HTML:\n",
  1208. $tree->as_HTML, "\n";
  1209. # Now that we're done with it, we must destroy it.
  1210. $tree = $tree->delete;
  1211. }
  1212. =head1 DESCRIPTION
  1213. (This class is part of the L<HTML::Tree|HTML::Tree> dist.)
  1214. This class is for HTML syntax trees that get built out of HTML
  1215. source. The way to use it is to:
  1216. 1. start a new (empty) HTML::TreeBuilder object,
  1217. 2. then use one of the methods from HTML::Parser (presumably with
  1218. $tree->parse_file($filename) for files, or with
  1219. $tree->parse($document_content) and $tree->eof if you've got
  1220. the content in a string) to parse the HTML
  1221. document into the tree $tree.
  1222. (You can combine steps 1 and 2 with the "new_from_file" or
  1223. "new_from_content" methods.)
  1224. 2b. call $root-E<gt>elementify() if you want.
  1225. 3. do whatever you need to do with the syntax tree, presumably
  1226. involving traversing it looking for some bit of information in it,
  1227. 4. and finally, when you're done with the tree, call $tree->delete() to
  1228. erase the contents of the tree from memory. This kind of thing
  1229. usually isn't necessary with most Perl objects, but it's necessary for
  1230. TreeBuilder objects. See L<HTML::Element|HTML::Element> for a more verbose
  1231. explanation of why this is the case.
  1232. =head1 METHODS AND ATTRIBUTES
  1233. Objects of this class inherit the methods of both HTML::Parser and
  1234. HTML::Element. The methods inherited from HTML::Parser are used for
  1235. building the HTML tree, and the methods inherited from HTML::Element
  1236. are what you use to scrutinize the tree. Besides this
  1237. (HTML::TreeBuilder) documentation, you must also carefully read the
  1238. HTML::Element documentation, and also skim the HTML::Parser
  1239. documentation -- probably only its parse and parse_file methods are of
  1240. interest.
  1241. The following methods native to HTML::TreeBuilder all control how
  1242. parsing takes place; they should be set I<before> you try parsing into
  1243. the given object. You can set the attributes by passing a TRUE or
  1244. FALSE value as argument. E.g., $root->implicit_tags returns the current
  1245. setting for the implicit_tags option, $root->implicit_tags(1) turns that
  1246. option on, and $root->implicit_tags(0) turns it off.
  1247. =over 4
  1248. =item $root = HTML::TreeBuilder->new_from_file(...)
  1249. This "shortcut" constructor merely combines constructing a new object
  1250. (with the "new" method, below), and calling $new->parse_file(...) on
  1251. it. Returns the new object. Note that this provides no way of
  1252. setting any parse options like store_comments (for that, call new, and
  1253. then set options, before calling parse_file). See the notes (below)
  1254. on parameters to parse_file.
  1255. =item $root = HTML::TreeBuilder->new_from_content(...)
  1256. This "shortcut" constructor merely combines constructing a new object
  1257. (with the "new" method, below), and calling for(...){$new->parse($_)}
  1258. and $new->eof on it. Returns the new object. Note that this provides
  1259. no way of setting any parse options like store_comments (for that,
  1260. call new, and then set options, before calling parse_file). Example
  1261. usages: HTML::TreeBuilder->new_from_content(@lines), or
  1262. HTML::TreeBuilder->new_from_content($content)
  1263. =item $root = HTML::TreeBuilder->new()
  1264. This creates a new HTML::TreeBuilder object. This method takes no
  1265. attributes.
  1266. =item $root->parse_file(...)
  1267. [An important method inherited from L<HTML::Parser|HTML::Parser>, which
  1268. see. Current versions of HTML::Parser can take a filespec, or a
  1269. filehandle object, like *FOO, or some object from class IO::Handle,
  1270. IO::File, IO::Socket) or the like.
  1271. I think you should check that a given file exists I<before> calling
  1272. $root->parse_file($filespec).]
  1273. =item $root->parse(...)
  1274. [A important method inherited from L<HTML::Parser|HTML::Parser>, which
  1275. see. See the note below for $root->eof().]
  1276. =item $root->eof()
  1277. This signals that you're finished parsing content into this tree; this
  1278. runs various kinds of crucial cleanup on the tree. This is called
  1279. I<for you> when you call $root->parse_file(...), but not when
  1280. you call $root->parse(...). So if you call
  1281. $root->parse(...), then you I<must> call $root->eof()
  1282. once you've finished feeding all the chunks to parse(...), and
  1283. before you actually start doing anything else with the tree in C<$root>.
  1284. =item $root->delete()
  1285. [An important method inherited from L<HTML::Element|HTML::Element>, which
  1286. see.]
  1287. =item $root->elementify()
  1288. This changes the class of the object in $root from
  1289. HTML::TreeBuilder to the class used for all the rest of the elements
  1290. in that tree (generally HTML::Element). Returns $root.
  1291. For most purposes, this is unnecessary, but if you call this after
  1292. you're finished building a tree, then it keeps you from accidentally
  1293. trying to call anything but HTML::Element methods on it. (I.e., if
  1294. you accidentally call C<$root-E<gt>parse_file(...)> on the
  1295. already-complete and elementified tree, then instead of charging ahead
  1296. and I<wreaking havoc>, it'll throw a fatal error -- since C<$root> is
  1297. now an object just of class HTML::Element which has no C<parse_file>
  1298. method.
  1299. Note that elementify currently deletes all the private attributes of
  1300. $root except for "_tag", "_parent", "_content", "_pos", and
  1301. "_implicit". If anyone requests that I change this to leave in yet
  1302. more private attributes, I might do so, in future versions.
  1303. =item $root->implicit_tags(value)
  1304. Setting this attribute to true will instruct the parser to try to
  1305. deduce implicit elements and implicit end tags. If it is false you
  1306. get a parse tree that just reflects the text as it stands, which is
  1307. unlikely to be useful for anything but quick and dirty parsing.
  1308. (In fact, I'd be curious to hear from anyone who finds it useful to
  1309. have implicit_tags set to false.)
  1310. Default is true.
  1311. Implicit elements have the implicit() attribute set.
  1312. =item $root->implicit_body_p_tag(value)
  1313. This controls an aspect of implicit element behavior, if implicit_tags
  1314. is on: If a text element (PCDATA) or a phrasal element (such as
  1315. "E<lt>emE<gt>") is to be inserted under "E<lt>bodyE<gt>", two things
  1316. can happen: if implicit_body_p_tag is true, it's placed under a new,
  1317. implicit "E<lt>pE<gt>" tag. (Past DTDs suggested this was the only
  1318. correct behavior, and this is how past versions of this module
  1319. behaved.) But if implicit_body_p_tag is false, nothing is implicated
  1320. -- the PCDATA or phrasal element is simply placed under
  1321. "E<lt>bodyE<gt>". Default is false.
  1322. =item $root->ignore_unknown(value)
  1323. This attribute controls whether unknown tags should be represented as
  1324. elements in the parse tree, or whether they should be ignored.
  1325. Default is true (to ignore unknown tags.)
  1326. =item $root->ignore_text(value)
  1327. Do not represent the text content of elements. This saves space if
  1328. all you want is to examine the structure of the document. Default is
  1329. false.
  1330. =item $root->ignore_ignorable_whitespace(value)
  1331. If set to true, TreeBuilder will try to avoid
  1332. creating ignorable whitespace text nodes in the tree. Default is
  1333. true. (In fact, I'd be interested in hearing if there's ever a case
  1334. where you need this off, or where leaving it on leads to incorrect
  1335. behavior.)
  1336. =item $root->no_space_compacting(value)
  1337. This determines whether TreeBuilder compacts all whitespace strings
  1338. in the document (well, outside of PRE or TEXTAREA elements), or
  1339. leaves them alone. Normally (default, value of 0), each string of
  1340. contiguous whitespace in the document is turned into a single space.
  1341. But that's not done if no_space_compacting is set to 1.
  1342. Setting no_space_compacting to 1 might be useful if you want
  1343. to read in a tree just to make some minor changes to it before
  1344. writing it back out.
  1345. This method is experimental. If you use it, be sure to report
  1346. any problems you might have with it.
  1347. =item $root->p_strict(value)
  1348. If set to true (and it defaults to false), TreeBuilder will take a
  1349. narrower than normal view of what can be under a "p" element; if it sees
  1350. a non-phrasal element about to be inserted under a "p", it will close that
  1351. "p". Otherwise it will close p elements only for other "p"'s, headings,
  1352. and "form" (altho the latter may be removed in future versions).
  1353. For example, when going thru this snippet of code,
  1354. <p>stuff
  1355. <ul>
  1356. TreeBuilder will normally (with C<p_strict> false) put the "ul" element
  1357. under the "p" element. However, with C<p_strict> set to true, it will
  1358. close the "p" first.
  1359. In theory, there should be strictness options like this for other/all
  1360. elements besides just "p"; but I treat this as a specal case simply
  1361. because of the fact that "p" occurs so frequently and its end-tag is
  1362. omitted so often; and also because application of strictness rules
  1363. at parse-time across all elements often makes tiny errors in HTML
  1364. coding produce drastically bad parse-trees, in my experience.
  1365. If you find that you wish you had an option like this to enforce
  1366. content-models on all elements, then I suggest that what you want is
  1367. content-model checking as a stage after TreeBuilder has finished
  1368. parsing.
  1369. =item $root->store_comments(value)
  1370. This determines whether TreeBuilder will normally store comments found
  1371. while parsing content into C<$root>. Currently, this is off by default.
  1372. =item $root->store_declarations(value)
  1373. This determines whether TreeBuilder will normally store markup
  1374. declarations found while parsing content into C<$root>. Currently,
  1375. this is off by default.
  1376. It is somewhat of a known bug (to be fixed one of these days, if
  1377. anyone needs it?) that declarations in the preamble (before the "html"
  1378. start-tag) end up actually I<under> the "html" element.
  1379. =item $root->store_pis(value)
  1380. This determines whether TreeBuilder will normally store processing
  1381. instructions found while parsing content into C<$root> -- assuming a
  1382. recent version of HTML::Parser (old versions won't parse PIs
  1383. correctly). Currently, this is off (false) by default.
  1384. It is somewhat of a known bug (to be fixed one of these days, if
  1385. anyone needs it?) that PIs in the preamble (before the "html"
  1386. start-tag) end up actually I<under> the "html" element.
  1387. =item $root->warn(value)
  1388. This determines whether syntax errors during parsing should generate
  1389. warnings, emitted via Perl's C<warn> function.
  1390. This is off (false) by default.
  1391. =back
  1392. =head1 HTML AND ITS DISCONTENTS
  1393. HTML is rather harder to parse than people who write it generally
  1394. suspect.
  1395. Here's the problem: HTML is a kind of SGML that permits "minimization"
  1396. and "implication". In short, this means that you don't have to close
  1397. every tag you open (because the opening of a subsequent tag may
  1398. implicitly close it), and if you use a tag that can't occur in the
  1399. context you seem to using it in, under certain conditions the parser
  1400. will be able to realize you mean to leave the current context and
  1401. enter the new one, that being the only one that your code could
  1402. correctly be interpreted in.
  1403. Now, this would all work flawlessly and unproblematically if: 1) all
  1404. the rules that both prescribe and describe HTML were (and had been)
  1405. clearly set out, and 2) everyone was aware of these rules and wrote
  1406. their code in compliance to them.
  1407. However, it didn't happen that way, and so most HTML pages are
  1408. difficult if not impossible to correctly parse with nearly any set of
  1409. straightforward SGML rules. That's why the internals of
  1410. HTML::TreeBuilder consist of lots and lots of special cases -- instead
  1411. of being just a generic SGML parser with HTML DTD rules plugged in.
  1412. =head1 TRANSLATIONS?
  1413. The techniques that HTML::TreeBuilder uses to perform what I consider
  1414. very robust parses on everyday code are not things that can work only
  1415. in Perl. To date, the algorithms at the center of HTML::TreeBuilder
  1416. have been implemented only in Perl, as far as I know; and I don't
  1417. foresee getting around to implementing them in any other language any
  1418. time soon.
  1419. If, however, anyone is looking for a semester project for an applied
  1420. programming class (or if they merely enjoy I<extra-curricular>
  1421. masochism), they might do well to see about choosing as a topic the
  1422. implementation/adaptation of these routines to any other interesting
  1423. programming language that you feel currently suffers from a lack of
  1424. robust HTML-parsing. I welcome correspondence on this subject, and
  1425. point out that one can learn a great deal about languages by trying to
  1426. translate between them, and then comparing the result.
  1427. The HTML::TreeBuilder source may seem long and complex, but it is
  1428. rather well commented, and symbol names are generally
  1429. self-explanatory. (You are encouraged to read the Mozilla HTML parser
  1430. source for comparison.) Some of the complexity comes from little-used
  1431. features, and some of it comes from having the HTML tokenizer
  1432. (HTML::Parser) being a separate module, requiring somewhat of a
  1433. different interface than you'd find in a combined tokenizer and
  1434. tree-builder. But most of the length of the source comes from the fact
  1435. that it's essentially a long list of special cases, with lots and lots
  1436. of sanity-checking, and sanity-recovery -- because, as Roseanne
  1437. Rosannadanna once said, "it's always I<something>".
  1438. Users looking to compare several HTML parsers should look at the
  1439. source for Raggett's Tidy
  1440. (C<E<lt>http://www.w3.org/People/Raggett/tidy/E<gt>>),
  1441. Mozilla
  1442. (C<E<lt>http://www.mozilla.org/E<gt>>),
  1443. and possibly root around the browsers section of Yahoo
  1444. to find the various open-source ones
  1445. (C<E<lt>http://dir.yahoo.com/Computers_and_Internet/Software/Internet/World_Wide_Web/Browsers/E<gt>>).
  1446. =head1 BUGS
  1447. * Framesets seem to work correctly now. Email me if you get a strange
  1448. parse from a document with framesets.
  1449. * Really bad HTML code will, often as not, make for a somewhat
  1450. objectionable parse tree. Regrettable, but unavoidably true.
  1451. * If you're running with implicit_tags off (God help you!), consider
  1452. that $tree->content_list probably contains the tree or grove from the
  1453. parse, and not $tree itself (which will, oddly enough, be an implicit
  1454. 'html' element). This seems counter-intuitive and problematic; but
  1455. seeing as how almost no HTML ever parses correctly with implicit_tags
  1456. off, this interface oddity seems the least of your problems.
  1457. =head1 BUG REPORTS
  1458. When a document parses in a way different from how you think it
  1459. should, I ask that you report this to me as a bug. The first thing
  1460. you should do is copy the document, trim out as much of it as you can
  1461. while still producing the bug in question, and I<then> email me that
  1462. mini-document I<and> the code you're using to parse it, at C<[email protected]>.
  1463. Include a note as to how it
  1464. parses (presumably including its $tree->dump output), and then a
  1465. I<careful and clear> explanation of where you think the parser is
  1466. going astray, and how you would prefer that it work instead.
  1467. =head1 SEE ALSO
  1468. L<HTML::Tree>; L<HTML::Parser>, L<HTML::Element>, L<HTML::Tagset>
  1469. L<HTML::DOMbo>
  1470. =head1 COPYRIGHT
  1471. Copyright 1995-1998 Gisle Aas; copyright 1999-2001 Sean M. Burke.
  1472. This library is free software; you can redistribute it and/or
  1473. modify it under the same terms as Perl itself.
  1474. This program is distributed in the hope that it will be useful, but
  1475. without any warranty; without even the implied warranty of
  1476. merchantability or fitness for a particular purpose.
  1477. =head1 AUTHOR
  1478. Original author Gisle Aas E<lt>gisle@aas.noE<gt>; current maintainer
  1479. Sean M. Burke, E<lt>sburke@cpan.orgE<gt>
  1480. =cut
  1481. CUCUMBER AND ORANGE SALAD
  1482. Adapted from:
  1483. Holzner, Yupa. /Great Thai Cooking for My American Friends: Creative
  1484. Thai Dishes Made Easy/. Royal House 1989. ISBN:0930440277
  1485. Makes about four servings.
  1486. 1 small greenhouse cucumber, sliced thin.
  1487. 2 navel oranges, peeled, separated into segments (seeded if
  1488. necessary), and probably chopped into chunks.
  1489. Dressing:
  1490. 3 tablespoons rice vinegar
  1491. .5 teaspoon salt
  1492. 1 tablespoon sugar
  1493. 1 teaspoon roasted sesame seeds
  1494. .5 tablespoons mirin
  1495. Mix all ingredients in the dressing. Pour the dressing over the
  1496. oranges and cucumbers, and toss. Serve.
  1497. All ingredient quantities are approximate. Adjust to taste. Multipy
  1498. quantities for more servings.
  1499. Note: the sesame seeds you get in an American supermarket are almost
  1500. certain to be unroasted, suspiciously waxy-looking, and astronomically
  1501. overpriced. Good cheap sesame seeds are available at most Asian
  1502. markets -- they usually come roasted; if they're unroasted, roast them
  1503. in a skillet for a few short minutes as needed.
  1504. [End Recipe]