html.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. """HTML utilities suitable for global use."""
  2. from __future__ import unicode_literals
  3. import re
  4. import warnings
  5. from django.utils.deprecation import RemovedInDjango18Warning
  6. from django.utils.encoding import force_text, force_str
  7. from django.utils.functional import allow_lazy
  8. from django.utils.safestring import SafeData, mark_safe
  9. from django.utils import six
  10. from django.utils.six.moves.urllib.parse import quote, unquote, urlsplit, urlunsplit
  11. from django.utils.text import normalize_newlines
  12. from .html_parser import HTMLParser, HTMLParseError
  13. # Configuration for urlize() function.
  14. TRAILING_PUNCTUATION = ['.', ',', ':', ';', '.)', '"', '\'']
  15. WRAPPING_PUNCTUATION = [('(', ')'), ('<', '>'), ('[', ']'), ('&lt;', '&gt;'), ('"', '"'), ('\'', '\'')]
  16. # List of possible strings used for bullets in bulleted lists.
  17. DOTS = ['&middot;', '*', '\u2022', '&#149;', '&bull;', '&#8226;']
  18. unencoded_ampersands_re = re.compile(r'&(?!(\w+|#\d+);)')
  19. word_split_re = re.compile(r'(\s+)')
  20. simple_url_re = re.compile(r'^https?://\[?\w', re.IGNORECASE)
  21. simple_url_2_re = re.compile(r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)$', re.IGNORECASE)
  22. simple_email_re = re.compile(r'^\S+@\S+\.\S+$')
  23. link_target_attribute_re = re.compile(r'(<a [^>]*?)target=[^\s>]+')
  24. html_gunk_re = re.compile(r'(?:<br clear="all">|<i><\/i>|<b><\/b>|<em><\/em>|<strong><\/strong>|<\/?smallcaps>|<\/?uppercase>)', re.IGNORECASE)
  25. hard_coded_bullets_re = re.compile(r'((?:<p>(?:%s).*?[a-zA-Z].*?</p>\s*)+)' % '|'.join(re.escape(x) for x in DOTS), re.DOTALL)
  26. trailing_empty_content_re = re.compile(r'(?:<p>(?:&nbsp;|\s|<br \/>)*?</p>\s*)+\Z')
  27. def escape(text):
  28. """
  29. Returns the given text with ampersands, quotes and angle brackets encoded for use in HTML.
  30. """
  31. return mark_safe(force_text(text).replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;'))
  32. escape = allow_lazy(escape, six.text_type)
  33. _js_escapes = {
  34. ord('\\'): '\\u005C',
  35. ord('\''): '\\u0027',
  36. ord('"'): '\\u0022',
  37. ord('>'): '\\u003E',
  38. ord('<'): '\\u003C',
  39. ord('&'): '\\u0026',
  40. ord('='): '\\u003D',
  41. ord('-'): '\\u002D',
  42. ord(';'): '\\u003B',
  43. ord('\u2028'): '\\u2028',
  44. ord('\u2029'): '\\u2029'
  45. }
  46. # Escape every ASCII character with a value less than 32.
  47. _js_escapes.update((ord('%c' % z), '\\u%04X' % z) for z in range(32))
  48. def escapejs(value):
  49. """Hex encodes characters for use in JavaScript strings."""
  50. return mark_safe(force_text(value).translate(_js_escapes))
  51. escapejs = allow_lazy(escapejs, six.text_type)
  52. def conditional_escape(text):
  53. """
  54. Similar to escape(), except that it doesn't operate on pre-escaped strings.
  55. """
  56. if hasattr(text, '__html__'):
  57. return text.__html__()
  58. else:
  59. return escape(text)
  60. def format_html(format_string, *args, **kwargs):
  61. """
  62. Similar to str.format, but passes all arguments through conditional_escape,
  63. and calls 'mark_safe' on the result. This function should be used instead
  64. of str.format or % interpolation to build up small HTML fragments.
  65. """
  66. args_safe = map(conditional_escape, args)
  67. kwargs_safe = dict((k, conditional_escape(v)) for (k, v) in six.iteritems(kwargs))
  68. return mark_safe(format_string.format(*args_safe, **kwargs_safe))
  69. def format_html_join(sep, format_string, args_generator):
  70. """
  71. A wrapper of format_html, for the common case of a group of arguments that
  72. need to be formatted using the same format string, and then joined using
  73. 'sep'. 'sep' is also passed through conditional_escape.
  74. 'args_generator' should be an iterator that returns the sequence of 'args'
  75. that will be passed to format_html.
  76. Example:
  77. format_html_join('\n', "<li>{0} {1}</li>", ((u.first_name, u.last_name)
  78. for u in users))
  79. """
  80. return mark_safe(conditional_escape(sep).join(
  81. format_html(format_string, *tuple(args))
  82. for args in args_generator))
  83. def linebreaks(value, autoescape=False):
  84. """Converts newlines into <p> and <br />s."""
  85. value = normalize_newlines(value)
  86. paras = re.split('\n{2,}', value)
  87. if autoescape:
  88. paras = ['<p>%s</p>' % escape(p).replace('\n', '<br />') for p in paras]
  89. else:
  90. paras = ['<p>%s</p>' % p.replace('\n', '<br />') for p in paras]
  91. return '\n\n'.join(paras)
  92. linebreaks = allow_lazy(linebreaks, six.text_type)
  93. class MLStripper(HTMLParser):
  94. def __init__(self):
  95. if six.PY2:
  96. HTMLParser.__init__(self)
  97. else:
  98. HTMLParser.__init__(self, strict=False)
  99. self.reset()
  100. self.fed = []
  101. def handle_data(self, d):
  102. self.fed.append(d)
  103. def handle_entityref(self, name):
  104. self.fed.append('&%s;' % name)
  105. def handle_charref(self, name):
  106. self.fed.append('&#%s;' % name)
  107. def get_data(self):
  108. return ''.join(self.fed)
  109. def _strip_once(value):
  110. """
  111. Internal tag stripping utility used by strip_tags.
  112. """
  113. s = MLStripper()
  114. try:
  115. s.feed(value)
  116. except HTMLParseError:
  117. return value
  118. try:
  119. s.close()
  120. except (HTMLParseError, UnboundLocalError):
  121. # UnboundLocalError because of http://bugs.python.org/issue17802
  122. # on Python 3.2, triggered by strict=False mode of HTMLParser
  123. return s.get_data() + s.rawdata
  124. else:
  125. return s.get_data()
  126. def strip_tags(value):
  127. """Returns the given HTML with all tags stripped."""
  128. # Note: in typical case this loop executes _strip_once once. Loop condition
  129. # is redundant, but helps to reduce number of executions of _strip_once.
  130. while '<' in value and '>' in value:
  131. new_value = _strip_once(value)
  132. if new_value == value:
  133. # _strip_once was not able to detect more tags
  134. break
  135. value = new_value
  136. return value
  137. strip_tags = allow_lazy(strip_tags)
  138. def remove_tags(html, tags):
  139. """Returns the given HTML with given tags removed."""
  140. tags = [re.escape(tag) for tag in tags.split()]
  141. tags_re = '(%s)' % '|'.join(tags)
  142. starttag_re = re.compile(r'<%s(/?>|(\s+[^>]*>))' % tags_re, re.U)
  143. endtag_re = re.compile('</%s>' % tags_re)
  144. html = starttag_re.sub('', html)
  145. html = endtag_re.sub('', html)
  146. return html
  147. remove_tags = allow_lazy(remove_tags, six.text_type)
  148. def strip_spaces_between_tags(value):
  149. """Returns the given HTML with spaces between tags removed."""
  150. return re.sub(r'>\s+<', '><', force_text(value))
  151. strip_spaces_between_tags = allow_lazy(strip_spaces_between_tags, six.text_type)
  152. def strip_entities(value):
  153. """Returns the given HTML with all entities (&something;) stripped."""
  154. return re.sub(r'&(?:\w+|#\d+);', '', force_text(value))
  155. strip_entities = allow_lazy(strip_entities, six.text_type)
  156. def fix_ampersands(value):
  157. """Returns the given HTML with all unencoded ampersands encoded correctly."""
  158. # As fix_ampersands is wrapped in allow_lazy, stacklevel 3 is more useful than 2.
  159. warnings.warn("The fix_ampersands function is deprecated and will be removed in Django 1.8.",
  160. RemovedInDjango18Warning, stacklevel=3)
  161. return unencoded_ampersands_re.sub('&amp;', force_text(value))
  162. fix_ampersands = allow_lazy(fix_ampersands, six.text_type)
  163. def smart_urlquote(url):
  164. "Quotes a URL if it isn't already quoted."
  165. # Handle IDN before quoting.
  166. try:
  167. scheme, netloc, path, query, fragment = urlsplit(url)
  168. try:
  169. netloc = netloc.encode('idna').decode('ascii') # IDN -> ACE
  170. except UnicodeError: # invalid domain part
  171. pass
  172. else:
  173. url = urlunsplit((scheme, netloc, path, query, fragment))
  174. except ValueError:
  175. # invalid IPv6 URL (normally square brackets in hostname part).
  176. pass
  177. url = unquote(force_str(url))
  178. # See http://bugs.python.org/issue2637
  179. url = quote(url, safe=b'!*\'();:@&=+$,/?#[]~')
  180. return force_text(url)
  181. def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
  182. """
  183. Converts any URLs in text into clickable links.
  184. Works on http://, https://, www. links, and also on links ending in one of
  185. the original seven gTLDs (.com, .edu, .gov, .int, .mil, .net, and .org).
  186. Links can have trailing punctuation (periods, commas, close-parens) and
  187. leading punctuation (opening parens) and it'll still do the right thing.
  188. If trim_url_limit is not None, the URLs in the link text longer than this
  189. limit will be truncated to trim_url_limit-3 characters and appended with
  190. an ellipsis.
  191. If nofollow is True, the links will get a rel="nofollow" attribute.
  192. If autoescape is True, the link text and URLs will be autoescaped.
  193. """
  194. def trim_url(x, limit=trim_url_limit):
  195. if limit is None or len(x) <= limit:
  196. return x
  197. return '%s...' % x[:max(0, limit - 3)]
  198. safe_input = isinstance(text, SafeData)
  199. words = word_split_re.split(force_text(text))
  200. for i, word in enumerate(words):
  201. if '.' in word or '@' in word or ':' in word:
  202. # Deal with punctuation.
  203. lead, middle, trail = '', word, ''
  204. for punctuation in TRAILING_PUNCTUATION:
  205. if middle.endswith(punctuation):
  206. middle = middle[:-len(punctuation)]
  207. trail = punctuation + trail
  208. for opening, closing in WRAPPING_PUNCTUATION:
  209. if middle.startswith(opening):
  210. middle = middle[len(opening):]
  211. lead = lead + opening
  212. # Keep parentheses at the end only if they're balanced.
  213. if (middle.endswith(closing)
  214. and middle.count(closing) == middle.count(opening) + 1):
  215. middle = middle[:-len(closing)]
  216. trail = closing + trail
  217. # Make URL we want to point to.
  218. url = None
  219. nofollow_attr = ' rel="nofollow"' if nofollow else ''
  220. if simple_url_re.match(middle):
  221. url = smart_urlquote(middle)
  222. elif simple_url_2_re.match(middle):
  223. url = smart_urlquote('http://%s' % middle)
  224. elif ':' not in middle and simple_email_re.match(middle):
  225. local, domain = middle.rsplit('@', 1)
  226. try:
  227. domain = domain.encode('idna').decode('ascii')
  228. except UnicodeError:
  229. continue
  230. url = 'mailto:%s@%s' % (local, domain)
  231. nofollow_attr = ''
  232. # Make link.
  233. if url:
  234. trimmed = trim_url(middle)
  235. if autoescape and not safe_input:
  236. lead, trail = escape(lead), escape(trail)
  237. url, trimmed = escape(url), escape(trimmed)
  238. middle = '<a href="%s"%s>%s</a>' % (url, nofollow_attr, trimmed)
  239. words[i] = mark_safe('%s%s%s' % (lead, middle, trail))
  240. else:
  241. if safe_input:
  242. words[i] = mark_safe(word)
  243. elif autoescape:
  244. words[i] = escape(word)
  245. elif safe_input:
  246. words[i] = mark_safe(word)
  247. elif autoescape:
  248. words[i] = escape(word)
  249. return ''.join(words)
  250. urlize = allow_lazy(urlize, six.text_type)
  251. def clean_html(text):
  252. """
  253. Clean the given HTML. Specifically, do the following:
  254. * Convert <b> and <i> to <strong> and <em>.
  255. * Encode all ampersands correctly.
  256. * Remove all "target" attributes from <a> tags.
  257. * Remove extraneous HTML, such as presentational tags that open and
  258. immediately close and <br clear="all">.
  259. * Convert hard-coded bullets into HTML unordered lists.
  260. * Remove stuff like "<p>&nbsp;&nbsp;</p>", but only if it's at the
  261. bottom of the text.
  262. """
  263. # As clean_html is wrapped in allow_lazy, stacklevel 3 is more useful than 2.
  264. warnings.warn("The clean_html function is deprecated and will be removed in Django 1.8.",
  265. RemovedInDjango18Warning, stacklevel=3)
  266. text = normalize_newlines(text)
  267. text = re.sub(r'<(/?)\s*b\s*>', '<\\1strong>', text)
  268. text = re.sub(r'<(/?)\s*i\s*>', '<\\1em>', text)
  269. text = fix_ampersands(text)
  270. # Remove all target="" attributes from <a> tags.
  271. text = link_target_attribute_re.sub('\\1', text)
  272. # Trim stupid HTML such as <br clear="all">.
  273. text = html_gunk_re.sub('', text)
  274. # Convert hard-coded bullets into HTML unordered lists.
  275. def replace_p_tags(match):
  276. s = match.group().replace('</p>', '</li>')
  277. for d in DOTS:
  278. s = s.replace('<p>%s' % d, '<li>')
  279. return '<ul>\n%s\n</ul>' % s
  280. text = hard_coded_bullets_re.sub(replace_p_tags, text)
  281. # Remove stuff like "<p>&nbsp;&nbsp;</p>", but only if it's at the bottom
  282. # of the text.
  283. text = trailing_empty_content_re.sub('', text)
  284. return text
  285. clean_html = allow_lazy(clean_html, six.text_type)
  286. def avoid_wrapping(value):
  287. """
  288. Avoid text wrapping in the middle of a phrase by adding non-breaking
  289. spaces where there previously were normal spaces.
  290. """
  291. return value.replace(" ", "\xa0")