1 """Utilities for working with HTML."""
3 from html5lib import sanitizer, serializer, tokenizer, treebuilders, treewalkers
4 from forum.utils.html2text import HTML2Text
5 from django.template import mark_safe
6 from forum import settings
8 class HTMLSanitizerMixin(sanitizer.HTMLSanitizerMixin):
9 acceptable_elements = ('a', 'abbr', 'acronym', 'address', 'b', 'big',
10 'blockquote', 'br', 'caption', 'center', 'cite', 'code', 'col',
11 'colgroup', 'dd', 'del', 'dfn', 'dir', 'div', 'dl', 'dt', 'em', 'font',
12 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'ins', 'kbd',
13 'li', 'ol', 'p', 'pre', 'q', 's', 'samp', 'small', 'span', 'strike',
14 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead',
15 'tr', 'tt', 'u', 'ul', 'var')
17 acceptable_attributes = ('abbr', 'align', 'alt', 'axis', 'border',
18 'cellpadding', 'cellspacing', 'char', 'charoff', 'charset', 'cite',
19 'cols', 'colspan', 'datetime', 'dir', 'frame', 'headers', 'height',
20 'href', 'hreflang', 'hspace', 'lang', 'longdesc', 'name', 'nohref',
21 'noshade', 'nowrap', 'rel', 'rev', 'rows', 'rowspan', 'rules', 'scope',
22 'span', 'src', 'start', 'summary', 'title', 'type', 'valign', 'vspace',
25 allowed_elements = acceptable_elements
26 allowed_attributes = acceptable_attributes
27 allowed_css_properties = ()
28 allowed_css_keywords = ()
29 allowed_svg_properties = ()
31 class HTMLSanitizer(tokenizer.HTMLTokenizer, HTMLSanitizerMixin):
34 for token in tokenizer.HTMLTokenizer.__iter__(self):
35 token = self.sanitize_token(token)
39 def sanitize_html(html):
40 """Sanitizes an HTML fragment."""
41 p = html5lib.HTMLParser(tokenizer=HTMLSanitizer,
42 tree=treebuilders.getTreeBuilder("dom"))
43 dom_tree = p.parseFragment(html)
44 walker = treewalkers.getTreeWalker("dom")
45 stream = walker(dom_tree)
46 s = serializer.HTMLSerializer(omit_optional_tags=False,
47 quote_attr_values=True)
48 output_generator = s.serialize(stream)
49 return u''.join(output_generator)
52 def html2text(s, ignore_tags=(), indent_width=4, page_width=80):
53 ignore_tags = [t.lower() for t in ignore_tags]
54 parser = HTML2Text(ignore_tags, indent_width, page_width)
58 return mark_safe(parser.result)
60 def buildtag(name, content, **attrs):
61 return mark_safe('<%s %s>%s</%s>' % (name, " ".join('%s="%s"' % i for i in attrs.items()), str(content), name))
63 def hyperlink(url, title, **attrs):
64 return mark_safe('<a href="%s" %s>%s</a>' % (url, " ".join('%s="%s"' % i for i in attrs.items()), title))
66 def objlink(obj, **attrs):
67 return hyperlink(settings.APP_URL + obj.get_absolute_url(), unicode(obj), **attrs)