# -*- coding: utf-8 -*- from __future__ import unicode_literals import logging import re import html5lib from html5lib.sanitizer import HTMLSanitizer from html5lib.serializer.htmlserializer import HTMLSerializer from . import callbacks as linkify_callbacks from .encoding import force_unicode from .sanitizer import BleachSanitizer VERSION = (1, 4, 2) __version__ = '.'.join([str(n) for n in VERSION]) __all__ = ['clean', 'linkify'] log = logging.getLogger('bleach') ALLOWED_TAGS = [ 'a', 'abbr', 'acronym', 'b', 'blockquote', 'code', 'em', 'i', 'li', 'ol', 'strong', 'ul', ] ALLOWED_ATTRIBUTES = { 'a': ['href', 'title'], 'abbr': ['title'], 'acronym': ['title'], } ALLOWED_STYLES = [] TLDS = """ac ad ae aero af ag ai al am an ao aq ar arpa as asia at au aw ax az ba bb bd be bf bg bh bi biz bj bm bn bo br bs bt bv bw by bz ca cat cc cd cf cg ch ci ck cl cm cn co com coop cr cu cv cx cy cz de dj dk dm do dz ec edu ee eg er es et eu fi fj fk fm fo fr ga gb gd ge gf gg gh gi gl gm gn gov gp gq gr gs gt gu gw gy hk hm hn hr ht hu id ie il im in info int io iq ir is it je jm jo jobs jp ke kg kh ki km kn kp kr kw ky kz la lb lc li lk lr ls lt lu lv ly ma mc md me mg mh mil mk ml mm mn mo mobi mp mq mr ms mt mu museum mv mw mx my mz na name nc ne net nf ng ni nl no np nr nu nz om org pa pe pf pg ph pk pl pm pn post pr pro ps pt pw py qa re ro rs ru rw sa sb sc sd se sg sh si sj sk sl sm sn so sr ss st su sv sx sy sz tc td tel tf tg th tj tk tl tm tn to tp tr travel tt tv tw tz ua ug uk us uy uz va vc ve vg vi vn vu wf ws xn xxx ye yt yu za zm zw""".split() # Make sure that .com doesn't get matched by .co first TLDS.reverse() PROTOCOLS = HTMLSanitizer.acceptable_protocols url_re = re.compile( r"""\(* # Match any opening parentheses. \b(?"]*)? # /path/zz (excluding "unsafe" chars from RFC 1738, # except for # and ~, which happen in practice) """.format('|'.join(PROTOCOLS), '|'.join(TLDS)), re.IGNORECASE | re.VERBOSE | re.UNICODE) proto_re = re.compile(r'^[\w-]+:/{0,3}', re.IGNORECASE) punct_re = re.compile(r'([\.,]+)$') email_re = re.compile( r"""(? tag replaced by the text within it adj = replace_nodes(tree, _text, node, current_child) current_child -= 1 # pull back current_child by 1 to scan the # new nodes again. else: text = force_unicode(attrs.pop('_text')) for attr_key, attr_val in attrs.items(): node.set(attr_key, attr_val) for n in reversed(list(node)): node.remove(n) text = parser.parseFragment(text) node.text = text.text for n in text: node.append(n) _seen.add(node) elif current_child >= 0: if node.tag == ETREE_TAG('pre') and skip_pre: linkify_nodes(node, False) elif not (node in _seen): linkify_nodes(node, True) current_child += 1 def email_repl(match): addr = match.group(0).replace('"', '"') link = { '_text': addr, 'href': 'mailto:{0!s}'.format(addr), } link = apply_callbacks(link, True) if link is None: return addr _href = link.pop('href') _text = link.pop('_text') repl = '{2!s}' attr = '{0!s}="{1!s}"' attribs = ' '.join(attr.format(k, v) for k, v in link.items()) return repl.format(_href, attribs, _text) def link_repl(match): url = match.group(0) open_brackets = close_brackets = 0 if url.startswith('('): _wrapping = strip_wrapping_parentheses(url) url, open_brackets, close_brackets = _wrapping end = '' m = re.search(punct_re, url) if m: end = m.group(0) url = url[0:m.start()] if re.search(proto_re, url): href = url else: href = ''.join(['http://', url]) link = { '_text': url, 'href': href, } link = apply_callbacks(link, True) if link is None: return '(' * open_brackets + url + ')' * close_brackets _text = link.pop('_text') _href = link.pop('href') repl = '{0!s}{3!s}{4!s}{5!s}' attr = '{0!s}="{1!s}"' attribs = ' '.join(attr.format(k, v) for k, v in link.items()) return repl.format('(' * open_brackets, _href, attribs, _text, end, ')' * close_brackets) try: linkify_nodes(forest) except RuntimeError as e: # If we hit the max recursion depth, just return what we've got. log.exception('Probable recursion error: {0!r}'.format(e)) return _render(forest) def _render(tree): """Try rendering as HTML, then XML, then give up.""" return force_unicode(_serialize(tree)) def _serialize(domtree): walker = html5lib.treewalkers.getTreeWalker('etree') stream = walker(domtree) serializer = HTMLSerializer(quote_attr_values=True, alphabetical_attributes=True, omit_optional_tags=False) return serializer.render(stream)