<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">#!/usr/bin/perl
package IkiWiki::Plugin::htmlbalance;

# htmlbalance: Parse and re-serialize HTML to ensure balanced tags
#
# Copyright 2008 Simon McVittie &lt;http://smcv.pseudorandom.co.uk/&gt;
# Licensed under the GNU GPL, version 2, or any later version published by the
# Free Software Foundation

use warnings;
use strict;
use IkiWiki 3.00;
use HTML::Entities;

sub import {
	hook(type =&gt; "getsetup", id =&gt; "htmlbalance", call =&gt; \&amp;getsetup);
	hook(type =&gt; "sanitize", id =&gt; "htmlbalance", call =&gt; \&amp;sanitize);
}

sub getsetup () {
	return
		plugin =&gt; {
			safe =&gt; 1,
			rebuild =&gt; undef,
		},
}

sub sanitize (@) {
	my %params=@_;
	my $ret = '';

	eval q{use HTML::TreeBuilder};
	error $@ if $@;
	my $tree = HTML::TreeBuilder-&gt;new();
	$tree-&gt;ignore_unknown(0);
	$tree-&gt;ignore_ignorable_whitespace(0);
	$tree-&gt;no_space_compacting(1);
	$tree-&gt;p_strict(1);
	$tree-&gt;store_comments(0);
	$tree-&gt;store_declarations(0);
	$tree-&gt;store_pis(0);
	$tree-&gt;parse_content($params{content});
	my @nodes = $tree-&gt;disembowel();
	foreach my $node (@nodes) {
		if (ref $node) {
			$ret .= $node-&gt;as_HTML(undef, '', {});
			chomp $ret;
			$node-&gt;delete();
		}
		else {
			$ret .= encode_entities($node);
		}
	}
	$tree-&gt;delete();
	return $ret;
}

1
</pre></body></html>