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