summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/htmlbalance.pm
blob: 3a2d62d15d47feb20886b594a51d3bc231e62a1b (plain)
  1. #!/usr/bin/perl
  2. package IkiWiki::Plugin::htmlbalance;
  3. # htmlbalance: Parse and re-serialize HTML to ensure balanced tags
  4. #
  5. # Copyright 2008 Simon McVittie <http://smcv.pseudorandom.co.uk/>
  6. # Licensed under the GNU GPL, version 2, or any later version published by the
  7. # Free Software Foundation
  8. use warnings;
  9. use strict;
  10. use IkiWiki 2.00;
  11. use HTML::TreeBuilder;
  12. use HTML::Entities;
  13. sub import { #{{{
  14. hook(type => "getsetup", id => "htmlbalance", call => \&getsetup);
  15. hook(type => "sanitize", id => "htmlbalance", call => \&sanitize);
  16. } # }}}
  17. sub getsetup () { #{{{
  18. return
  19. plugin => {
  20. safe => 1,
  21. rebuild => undef,
  22. },
  23. } #}}}
  24. sub sanitize (@) { #{{{
  25. my %params=@_;
  26. my $ret = '';
  27. my $tree = HTML::TreeBuilder->new_from_content($params{content});
  28. my @nodes = $tree->disembowel();
  29. foreach my $node (@nodes) {
  30. if (ref $node) {
  31. $ret .= $node->as_XML();
  32. chomp $ret;
  33. $node->delete();
  34. }
  35. else {
  36. $ret .= encode_entities($node);
  37. }
  38. }
  39. $tree->delete();
  40. return $ret;
  41. } # }}}
  42. 1