linkifier.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. from __future__ import unicode_literals
  2. import re
  3. import six
  4. from bleach import callbacks as linkify_callbacks
  5. from bleach import html5lib_shim
  6. from bleach.utils import alphabetize_attributes, force_unicode
  7. #: List of default callbacks
  8. DEFAULT_CALLBACKS = [linkify_callbacks.nofollow]
  9. TLDS = """ac ad ae aero af ag ai al am an ao aq ar arpa as asia at au aw ax az
  10. ba bb bd be bf bg bh bi biz bj bm bn bo br bs bt bv bw by bz ca cat
  11. cc cd cf cg ch ci ck cl cm cn co com coop cr cu cv cx cy cz de dj dk
  12. dm do dz ec edu ee eg er es et eu fi fj fk fm fo fr ga gb gd ge gf gg
  13. gh gi gl gm gn gov gp gq gr gs gt gu gw gy hk hm hn hr ht hu id ie il
  14. im in info int io iq ir is it je jm jo jobs jp ke kg kh ki km kn kp
  15. kr kw ky kz la lb lc li lk lr ls lt lu lv ly ma mc md me mg mh mil mk
  16. ml mm mn mo mobi mp mq mr ms mt mu museum mv mw mx my mz na name nc ne
  17. net nf ng ni nl no np nr nu nz om org pa pe pf pg ph pk pl pm pn post
  18. pr pro ps pt pw py qa re ro rs ru rw sa sb sc sd se sg sh si sj sk sl
  19. sm sn so sr ss st su sv sx sy sz tc td tel tf tg th tj tk tl tm tn to
  20. tp tr travel tt tv tw tz ua ug uk us uy uz va vc ve vg vi vn vu wf ws
  21. xn xxx ye yt yu za zm zw""".split()
  22. # Make sure that .com doesn't get matched by .co first
  23. TLDS.reverse()
  24. def build_url_re(tlds=TLDS, protocols=html5lib_shim.allowed_protocols):
  25. """Builds the url regex used by linkifier
  26. If you want a different set of tlds or allowed protocols, pass those in
  27. and stomp on the existing ``url_re``::
  28. from bleach import linkifier
  29. my_url_re = linkifier.build_url_re(my_tlds_list, my_protocols)
  30. linker = LinkifyFilter(url_re=my_url_re)
  31. """
  32. return re.compile(
  33. r"""\(* # Match any opening parentheses.
  34. \b(?<![@.])(?:(?:{0}):/{{0,3}}(?:(?:\w+:)?\w+@)?)? # http://
  35. ([\w-]+\.)+(?:{1})(?:\:[0-9]+)?(?!\.\w)\b # xx.yy.tld(:##)?
  36. (?:[/?][^\s\{{\}}\|\\\^\[\]`<>"]*)?
  37. # /path/zz (excluding "unsafe" chars from RFC 1738,
  38. # except for # and ~, which happen in practice)
  39. """.format('|'.join(sorted(protocols)), '|'.join(sorted(tlds))),
  40. re.IGNORECASE | re.VERBOSE | re.UNICODE)
  41. URL_RE = build_url_re()
  42. PROTO_RE = re.compile(r'^[\w-]+:/{0,3}', re.IGNORECASE)
  43. def build_email_re(tlds=TLDS):
  44. """Builds the email regex used by linkifier
  45. If you want a different set of tlds, pass those in and stomp on the existing ``email_re``::
  46. from bleach import linkifier
  47. my_email_re = linkifier.build_email_re(my_tlds_list)
  48. linker = LinkifyFilter(email_re=my_url_re)
  49. """
  50. # open and closing braces doubled below for format string
  51. return re.compile(
  52. r"""(?<!//)
  53. (([-!#$%&'*+/=?^_`{{}}|~0-9A-Z]+
  54. (\.[-!#$%&'*+/=?^_`{{}}|~0-9A-Z]+)* # dot-atom
  55. |^"([\001-\010\013\014\016-\037!#-\[\]-\177]
  56. |\\[\001-\011\013\014\016-\177])*" # quoted-string
  57. )@(?:[A-Z0-9](?:[A-Z0-9-]{{0,61}}[A-Z0-9])?\.)+(?:{0})) # domain
  58. """.format('|'.join(tlds)),
  59. re.IGNORECASE | re.MULTILINE | re.VERBOSE)
  60. EMAIL_RE = build_email_re()
  61. class Linker(object):
  62. """Convert URL-like strings in an HTML fragment to links
  63. This function converts strings that look like URLs, domain names and email
  64. addresses in text that may be an HTML fragment to links, while preserving:
  65. 1. links already in the string
  66. 2. urls found in attributes
  67. 3. email addresses
  68. linkify does a best-effort approach and tries to recover from bad
  69. situations due to crazy text.
  70. """
  71. def __init__(self, callbacks=DEFAULT_CALLBACKS, skip_tags=None, parse_email=False,
  72. url_re=URL_RE, email_re=EMAIL_RE, recognized_tags=html5lib_shim.HTML_TAGS):
  73. """Creates a Linker instance
  74. :arg list callbacks: list of callbacks to run when adjusting tag attributes;
  75. defaults to ``bleach.linkifier.DEFAULT_CALLBACKS``
  76. :arg list skip_tags: list of tags that you don't want to linkify the
  77. contents of; for example, you could set this to ``['pre']`` to skip
  78. linkifying contents of ``pre`` tags
  79. :arg bool parse_email: whether or not to linkify email addresses
  80. :arg re url_re: url matching regex
  81. :arg re email_re: email matching regex
  82. :arg list-of-strings recognized_tags: the list of tags that linkify knows about;
  83. everything else gets escaped
  84. :returns: linkified text as unicode
  85. """
  86. self.callbacks = callbacks
  87. self.skip_tags = skip_tags
  88. self.parse_email = parse_email
  89. self.url_re = url_re
  90. self.email_re = email_re
  91. # Create a parser/tokenizer that allows all HTML tags and escapes
  92. # anything not in that list.
  93. self.parser = html5lib_shim.BleachHTMLParser(
  94. tags=recognized_tags,
  95. strip=False,
  96. consume_entities=True,
  97. namespaceHTMLElements=False,
  98. )
  99. self.walker = html5lib_shim.getTreeWalker('etree')
  100. self.serializer = html5lib_shim.BleachHTMLSerializer(
  101. quote_attr_values='always',
  102. omit_optional_tags=False,
  103. # linkify does not sanitize
  104. sanitize=False,
  105. # linkify alphabetizes
  106. alphabetical_attributes=False,
  107. )
  108. def linkify(self, text):
  109. """Linkify specified text
  110. :arg str text: the text to add links to
  111. :returns: linkified text as unicode
  112. :raises TypeError: if ``text`` is not a text type
  113. """
  114. if not isinstance(text, six.string_types):
  115. raise TypeError('argument must be of text type')
  116. text = force_unicode(text)
  117. if not text:
  118. return ''
  119. dom = self.parser.parseFragment(text)
  120. filtered = LinkifyFilter(
  121. source=self.walker(dom),
  122. callbacks=self.callbacks,
  123. skip_tags=self.skip_tags,
  124. parse_email=self.parse_email,
  125. url_re=self.url_re,
  126. email_re=self.email_re,
  127. )
  128. return self.serializer.render(filtered)
  129. class LinkifyFilter(html5lib_shim.Filter):
  130. """html5lib filter that linkifies text
  131. This will do the following:
  132. * convert email addresses into links
  133. * convert urls into links
  134. * edit existing links by running them through callbacks--the default is to
  135. add a ``rel="nofollow"``
  136. This filter can be used anywhere html5lib filters can be used.
  137. """
  138. def __init__(self, source, callbacks=None, skip_tags=None, parse_email=False,
  139. url_re=URL_RE, email_re=EMAIL_RE):
  140. """Creates a LinkifyFilter instance
  141. :arg TreeWalker source: stream
  142. :arg list callbacks: list of callbacks to run when adjusting tag attributes;
  143. defaults to ``bleach.linkifier.DEFAULT_CALLBACKS``
  144. :arg list skip_tags: list of tags that you don't want to linkify the
  145. contents of; for example, you could set this to ``['pre']`` to skip
  146. linkifying contents of ``pre`` tags
  147. :arg bool parse_email: whether or not to linkify email addresses
  148. :arg re url_re: url matching regex
  149. :arg re email_re: email matching regex
  150. """
  151. super(LinkifyFilter, self).__init__(source)
  152. self.callbacks = callbacks or []
  153. self.skip_tags = skip_tags or []
  154. self.parse_email = parse_email
  155. self.url_re = url_re
  156. self.email_re = email_re
  157. def apply_callbacks(self, attrs, is_new):
  158. """Given an attrs dict and an is_new bool, runs through callbacks
  159. Callbacks can return an adjusted attrs dict or ``None``. In the case of
  160. ``None``, we stop going through callbacks and return that and the link
  161. gets dropped.
  162. :arg dict attrs: map of ``(namespace, name)`` -> ``value``
  163. :arg bool is_new: whether or not this link was added by linkify
  164. :returns: adjusted attrs dict or ``None``
  165. """
  166. for cb in self.callbacks:
  167. attrs = cb(attrs, is_new)
  168. if attrs is None:
  169. return None
  170. return attrs
  171. def extract_character_data(self, token_list):
  172. """Extracts and squashes character sequences in a token stream"""
  173. # FIXME(willkg): This is a terrible idea. What it does is drop all the
  174. # tags from the token list and merge the Characters and SpaceCharacters
  175. # tokens into a single text.
  176. #
  177. # So something like this::
  178. #
  179. # "<span>" "<b>" "some text" "</b>" "</span>"
  180. #
  181. # gets converted to "some text".
  182. #
  183. # This gets used to figure out the ``_text`` fauxttribute value for
  184. # linkify callables.
  185. #
  186. # I'm not really sure how else to support that ``_text`` fauxttribute and
  187. # maintain some modicum of backwards compatibility with previous versions
  188. # of Bleach.
  189. out = []
  190. for token in token_list:
  191. token_type = token['type']
  192. if token_type in ['Characters', 'SpaceCharacters']:
  193. out.append(token['data'])
  194. return ''.join(out)
  195. def handle_email_addresses(self, src_iter):
  196. """Handle email addresses in character tokens"""
  197. for token in src_iter:
  198. if token['type'] == 'Characters':
  199. text = token['data']
  200. new_tokens = []
  201. end = 0
  202. # For each email address we find in the text
  203. for match in self.email_re.finditer(text):
  204. if match.start() > end:
  205. new_tokens.append(
  206. {'type': 'Characters', 'data': text[end:match.start()]}
  207. )
  208. # Run attributes through the callbacks to see what we
  209. # should do with this match
  210. attrs = {
  211. (None, 'href'): 'mailto:%s' % match.group(0),
  212. '_text': match.group(0)
  213. }
  214. attrs = self.apply_callbacks(attrs, True)
  215. if attrs is None:
  216. # Just add the text--but not as a link
  217. new_tokens.append(
  218. {'type': 'Characters', 'data': match.group(0)}
  219. )
  220. else:
  221. # Add an "a" tag for the new link
  222. _text = attrs.pop('_text', '')
  223. attrs = alphabetize_attributes(attrs)
  224. new_tokens.extend([
  225. {'type': 'StartTag', 'name': 'a', 'data': attrs},
  226. {'type': 'Characters', 'data': force_unicode(_text)},
  227. {'type': 'EndTag', 'name': 'a'}
  228. ])
  229. end = match.end()
  230. if new_tokens:
  231. # Yield the adjusted set of tokens and then continue
  232. # through the loop
  233. if end < len(text):
  234. new_tokens.append({'type': 'Characters', 'data': text[end:]})
  235. for new_token in new_tokens:
  236. yield new_token
  237. continue
  238. yield token
  239. def strip_non_url_bits(self, fragment):
  240. """Strips non-url bits from the url
  241. This accounts for over-eager matching by the regex.
  242. """
  243. prefix = suffix = ''
  244. while fragment:
  245. # Try removing ( from the beginning and, if it's balanced, from the
  246. # end, too
  247. if fragment.startswith('('):
  248. prefix = prefix + '('
  249. fragment = fragment[1:]
  250. if fragment.endswith(')'):
  251. suffix = ')' + suffix
  252. fragment = fragment[:-1]
  253. continue
  254. # Now try extraneous things from the end. For example, sometimes we
  255. # pick up ) at the end of a url, but the url is in a parenthesized
  256. # phrase like:
  257. #
  258. # "i looked at the site (at http://example.com)"
  259. if fragment.endswith(')') and '(' not in fragment:
  260. fragment = fragment[:-1]
  261. suffix = ')' + suffix
  262. continue
  263. # Handle commas
  264. if fragment.endswith(','):
  265. fragment = fragment[:-1]
  266. suffix = ',' + suffix
  267. continue
  268. # Handle periods
  269. if fragment.endswith('.'):
  270. fragment = fragment[:-1]
  271. suffix = '.' + suffix
  272. continue
  273. # Nothing matched, so we're done
  274. break
  275. return fragment, prefix, suffix
  276. def handle_links(self, src_iter):
  277. """Handle links in character tokens"""
  278. in_a = False # happens, if parse_email=True and if a mail was found
  279. for token in src_iter:
  280. if in_a:
  281. if token['type'] == 'EndTag' and token['name'] == 'a':
  282. in_a = False
  283. yield token
  284. continue
  285. elif token['type'] == 'StartTag' and token['name'] == 'a':
  286. in_a = True
  287. yield token
  288. continue
  289. if token['type'] == 'Characters':
  290. text = token['data']
  291. new_tokens = []
  292. end = 0
  293. for match in self.url_re.finditer(text):
  294. if match.start() > end:
  295. new_tokens.append(
  296. {'type': 'Characters', 'data': text[end:match.start()]}
  297. )
  298. url = match.group(0)
  299. prefix = suffix = ''
  300. # Sometimes we pick up too much in the url match, so look for
  301. # bits we should drop and remove them from the match
  302. url, prefix, suffix = self.strip_non_url_bits(url)
  303. # If there's no protocol, add one
  304. if PROTO_RE.search(url):
  305. href = url
  306. else:
  307. href = 'http://%s' % url
  308. attrs = {
  309. (None, 'href'): href,
  310. '_text': url
  311. }
  312. attrs = self.apply_callbacks(attrs, True)
  313. if attrs is None:
  314. # Just add the text
  315. new_tokens.append(
  316. {'type': 'Characters', 'data': prefix + url + suffix}
  317. )
  318. else:
  319. # Add the "a" tag!
  320. if prefix:
  321. new_tokens.append(
  322. {'type': 'Characters', 'data': prefix}
  323. )
  324. _text = attrs.pop('_text', '')
  325. attrs = alphabetize_attributes(attrs)
  326. new_tokens.extend([
  327. {'type': 'StartTag', 'name': 'a', 'data': attrs},
  328. {'type': 'Characters', 'data': force_unicode(_text)},
  329. {'type': 'EndTag', 'name': 'a'},
  330. ])
  331. if suffix:
  332. new_tokens.append(
  333. {'type': 'Characters', 'data': suffix}
  334. )
  335. end = match.end()
  336. if new_tokens:
  337. # Yield the adjusted set of tokens and then continue
  338. # through the loop
  339. if end < len(text):
  340. new_tokens.append({'type': 'Characters', 'data': text[end:]})
  341. for new_token in new_tokens:
  342. yield new_token
  343. continue
  344. yield token
  345. def handle_a_tag(self, token_buffer):
  346. """Handle the "a" tag
  347. This could adjust the link or drop it altogether depending on what the
  348. callbacks return.
  349. This yields the new set of tokens.
  350. """
  351. a_token = token_buffer[0]
  352. if a_token['data']:
  353. attrs = a_token['data']
  354. else:
  355. attrs = {}
  356. text = self.extract_character_data(token_buffer)
  357. attrs['_text'] = text
  358. attrs = self.apply_callbacks(attrs, False)
  359. if attrs is None:
  360. # We're dropping the "a" tag and everything else and replacing
  361. # it with character data. So emit that token.
  362. yield {'type': 'Characters', 'data': text}
  363. else:
  364. new_text = attrs.pop('_text', '')
  365. a_token['data'] = alphabetize_attributes(attrs)
  366. if text == new_text:
  367. # The callbacks didn't change the text, so we yield the new "a"
  368. # token, then whatever else was there, then the end "a" token
  369. yield a_token
  370. for mem in token_buffer[1:]:
  371. yield mem
  372. else:
  373. # If the callbacks changed the text, then we're going to drop
  374. # all the tokens between the start and end "a" tags and replace
  375. # it with the new text
  376. yield a_token
  377. yield {'type': 'Characters', 'data': force_unicode(new_text)}
  378. yield token_buffer[-1]
  379. def __iter__(self):
  380. in_a = False
  381. in_skip_tag = None
  382. token_buffer = []
  383. for token in super(LinkifyFilter, self).__iter__():
  384. if in_a:
  385. # Handle the case where we're in an "a" tag--we want to buffer tokens
  386. # until we hit an end "a" tag.
  387. if token['type'] == 'EndTag' and token['name'] == 'a':
  388. # Add the end tag to the token buffer and then handle them
  389. # and yield anything returned
  390. token_buffer.append(token)
  391. for new_token in self.handle_a_tag(token_buffer):
  392. yield new_token
  393. # Clear "a" related state and continue since we've yielded all
  394. # the tokens we're going to yield
  395. in_a = False
  396. token_buffer = []
  397. else:
  398. token_buffer.append(token)
  399. continue
  400. if token['type'] in ['StartTag', 'EmptyTag']:
  401. if token['name'] in self.skip_tags:
  402. # Skip tags start a "special mode" where we don't linkify
  403. # anything until the end tag.
  404. in_skip_tag = token['name']
  405. elif token['name'] == 'a':
  406. # The "a" tag is special--we switch to a slurp mode and
  407. # slurp all the tokens until the end "a" tag and then
  408. # figure out what to do with them there.
  409. in_a = True
  410. token_buffer.append(token)
  411. # We buffer the start tag, so we don't want to yield it,
  412. # yet
  413. continue
  414. elif in_skip_tag and self.skip_tags:
  415. # NOTE(willkg): We put this clause here since in_a and
  416. # switching in and out of in_a takes precedence.
  417. if token['type'] == 'EndTag' and token['name'] == in_skip_tag:
  418. in_skip_tag = None
  419. elif not in_a and not in_skip_tag and token['type'] == 'Characters':
  420. new_stream = iter([token])
  421. if self.parse_email:
  422. new_stream = self.handle_email_addresses(new_stream)
  423. new_stream = self.handle_links(new_stream)
  424. for token in new_stream:
  425. yield token
  426. # We've already yielded this token, so continue
  427. continue
  428. yield token