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