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