html.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. """HTML utilities suitable for global use."""
  2. import html
  3. import json
  4. import re
  5. from html.parser import HTMLParser
  6. from urllib.parse import (
  7. parse_qsl, quote, unquote, urlencode, urlsplit, urlunsplit,
  8. )
  9. from django.utils.encoding import punycode
  10. from django.utils.functional import Promise, keep_lazy, keep_lazy_text
  11. from django.utils.http import RFC3986_GENDELIMS, RFC3986_SUBDELIMS
  12. from django.utils.safestring import SafeData, SafeString, mark_safe
  13. from django.utils.text import normalize_newlines
  14. # Configuration for urlize() function.
  15. TRAILING_PUNCTUATION_CHARS = '.,:;!'
  16. WRAPPING_PUNCTUATION = [('(', ')'), ('[', ']')]
  17. # List of possible strings used for bullets in bulleted lists.
  18. DOTS = ['·', '*', '\u2022', '•', '•', '•']
  19. unencoded_ampersands_re = re.compile(r'&(?!(\w+|#\d+);)')
  20. word_split_re = re.compile(r'''([\s<>"']+)''')
  21. simple_url_re = re.compile(r'^https?://\[?\w', re.IGNORECASE)
  22. simple_url_2_re = re.compile(r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)($|/.*)$', re.IGNORECASE)
  23. @keep_lazy(str, SafeString)
  24. def escape(text):
  25. """
  26. Return the given text with ampersands, quotes and angle brackets encoded
  27. for use in HTML.
  28. Always escape input, even if it's already escaped and marked as such.
  29. This may result in double-escaping. If this is a concern, use
  30. conditional_escape() instead.
  31. """
  32. return mark_safe(html.escape(str(text)))
  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('`'): '\\u0060',
  44. ord('\u2028'): '\\u2028',
  45. ord('\u2029'): '\\u2029'
  46. }
  47. # Escape every ASCII character with a value less than 32.
  48. _js_escapes.update((ord('%c' % z), '\\u%04X' % z) for z in range(32))
  49. @keep_lazy(str, SafeString)
  50. def escapejs(value):
  51. """Hex encode characters for use in JavaScript strings."""
  52. return mark_safe(str(value).translate(_js_escapes))
  53. _json_script_escapes = {
  54. ord('>'): '\\u003E',
  55. ord('<'): '\\u003C',
  56. ord('&'): '\\u0026',
  57. }
  58. def json_script(value, element_id):
  59. """
  60. Escape all the HTML/XML special characters with their unicode escapes, so
  61. value is safe to be output anywhere except for inside a tag attribute. Wrap
  62. the escaped JSON in a script tag.
  63. """
  64. from django.core.serializers.json import DjangoJSONEncoder
  65. json_str = json.dumps(value, cls=DjangoJSONEncoder).translate(_json_script_escapes)
  66. return format_html(
  67. '<script id="{}" type="application/json">{}</script>',
  68. element_id, mark_safe(json_str)
  69. )
  70. def conditional_escape(text):
  71. """
  72. Similar to escape(), except that it doesn't operate on pre-escaped strings.
  73. This function relies on the __html__ convention used both by Django's
  74. SafeData class and by third-party libraries like markupsafe.
  75. """
  76. if isinstance(text, Promise):
  77. text = str(text)
  78. if hasattr(text, '__html__'):
  79. return text.__html__()
  80. else:
  81. return escape(text)
  82. def format_html(format_string, *args, **kwargs):
  83. """
  84. Similar to str.format, but pass all arguments through conditional_escape(),
  85. and call mark_safe() on the result. This function should be used instead
  86. of str.format or % interpolation to build up small HTML fragments.
  87. """
  88. args_safe = map(conditional_escape, args)
  89. kwargs_safe = {k: conditional_escape(v) for (k, v) in kwargs.items()}
  90. return mark_safe(format_string.format(*args_safe, **kwargs_safe))
  91. def format_html_join(sep, format_string, args_generator):
  92. """
  93. A wrapper of format_html, for the common case of a group of arguments that
  94. need to be formatted using the same format string, and then joined using
  95. 'sep'. 'sep' is also passed through conditional_escape.
  96. 'args_generator' should be an iterator that returns the sequence of 'args'
  97. that will be passed to format_html.
  98. Example:
  99. format_html_join('\n', "<li>{} {}</li>", ((u.first_name, u.last_name)
  100. for u in users))
  101. """
  102. return mark_safe(conditional_escape(sep).join(
  103. format_html(format_string, *args)
  104. for args in args_generator
  105. ))
  106. @keep_lazy_text
  107. def linebreaks(value, autoescape=False):
  108. """Convert newlines into <p> and <br>s."""
  109. value = normalize_newlines(value)
  110. paras = re.split('\n{2,}', str(value))
  111. if autoescape:
  112. paras = ['<p>%s</p>' % escape(p).replace('\n', '<br>') for p in paras]
  113. else:
  114. paras = ['<p>%s</p>' % p.replace('\n', '<br>') for p in paras]
  115. return '\n\n'.join(paras)
  116. class MLStripper(HTMLParser):
  117. def __init__(self):
  118. super().__init__(convert_charrefs=False)
  119. self.reset()
  120. self.fed = []
  121. def handle_data(self, d):
  122. self.fed.append(d)
  123. def handle_entityref(self, name):
  124. self.fed.append('&%s;' % name)
  125. def handle_charref(self, name):
  126. self.fed.append('&#%s;' % name)
  127. def get_data(self):
  128. return ''.join(self.fed)
  129. def _strip_once(value):
  130. """
  131. Internal tag stripping utility used by strip_tags.
  132. """
  133. s = MLStripper()
  134. s.feed(value)
  135. s.close()
  136. return s.get_data()
  137. @keep_lazy_text
  138. def strip_tags(value):
  139. """Return the given HTML with all tags stripped."""
  140. # Note: in typical case this loop executes _strip_once once. Loop condition
  141. # is redundant, but helps to reduce number of executions of _strip_once.
  142. value = str(value)
  143. while '<' in value and '>' in value:
  144. new_value = _strip_once(value)
  145. if value.count('<') == new_value.count('<'):
  146. # _strip_once wasn't able to detect more tags.
  147. break
  148. value = new_value
  149. return value
  150. @keep_lazy_text
  151. def strip_spaces_between_tags(value):
  152. """Return the given HTML with spaces between tags removed."""
  153. return re.sub(r'>\s+<', '><', str(value))
  154. def smart_urlquote(url):
  155. """Quote a URL if it isn't already quoted."""
  156. def unquote_quote(segment):
  157. segment = unquote(segment)
  158. # Tilde is part of RFC3986 Unreserved Characters
  159. # https://tools.ietf.org/html/rfc3986#section-2.3
  160. # See also https://bugs.python.org/issue16285
  161. return quote(segment, safe=RFC3986_SUBDELIMS + RFC3986_GENDELIMS + '~')
  162. # Handle IDN before quoting.
  163. try:
  164. scheme, netloc, path, query, fragment = urlsplit(url)
  165. except ValueError:
  166. # invalid IPv6 URL (normally square brackets in hostname part).
  167. return unquote_quote(url)
  168. try:
  169. netloc = punycode(netloc) # IDN -> ACE
  170. except UnicodeError: # invalid domain part
  171. return unquote_quote(url)
  172. if query:
  173. # Separately unquoting key/value, so as to not mix querystring separators
  174. # included in query values. See #22267.
  175. query_parts = [(unquote(q[0]), unquote(q[1]))
  176. for q in parse_qsl(query, keep_blank_values=True)]
  177. # urlencode will take care of quoting
  178. query = urlencode(query_parts)
  179. path = unquote_quote(path)
  180. fragment = unquote_quote(fragment)
  181. return urlunsplit((scheme, netloc, path, query, fragment))
  182. @keep_lazy_text
  183. def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
  184. """
  185. Convert any URLs in text into clickable links.
  186. Works on http://, https://, www. links, and also on links ending in one of
  187. the original seven gTLDs (.com, .edu, .gov, .int, .mil, .net, and .org).
  188. Links can have trailing punctuation (periods, commas, close-parens) and
  189. leading punctuation (opening parens) and it'll still do the right thing.
  190. If trim_url_limit is not None, truncate the URLs in the link text longer
  191. than this limit to trim_url_limit - 1 characters and append an ellipsis.
  192. If nofollow is True, give the links a rel="nofollow" attribute.
  193. If autoescape is True, autoescape the link text and URLs.
  194. """
  195. safe_input = isinstance(text, SafeData)
  196. def trim_url(x, limit=trim_url_limit):
  197. if limit is None or len(x) <= limit:
  198. return x
  199. return '%s…' % x[:max(0, limit - 1)]
  200. def trim_punctuation(lead, middle, trail):
  201. """
  202. Trim trailing and wrapping punctuation from `middle`. Return the items
  203. of the new state.
  204. """
  205. # Continue trimming until middle remains unchanged.
  206. trimmed_something = True
  207. while trimmed_something:
  208. trimmed_something = False
  209. # Trim wrapping punctuation.
  210. for opening, closing in WRAPPING_PUNCTUATION:
  211. if middle.startswith(opening):
  212. middle = middle[len(opening):]
  213. lead += opening
  214. trimmed_something = True
  215. # Keep parentheses at the end only if they're balanced.
  216. if (middle.endswith(closing) and
  217. middle.count(closing) == middle.count(opening) + 1):
  218. middle = middle[:-len(closing)]
  219. trail = closing + trail
  220. trimmed_something = True
  221. # Trim trailing punctuation (after trimming wrapping punctuation,
  222. # as encoded entities contain ';'). Unescape entities to avoid
  223. # breaking them by removing ';'.
  224. middle_unescaped = html.unescape(middle)
  225. stripped = middle_unescaped.rstrip(TRAILING_PUNCTUATION_CHARS)
  226. if middle_unescaped != stripped:
  227. trail = middle[len(stripped):] + trail
  228. middle = middle[:len(stripped) - len(middle_unescaped)]
  229. trimmed_something = True
  230. return lead, middle, trail
  231. def is_email_simple(value):
  232. """Return True if value looks like an email address."""
  233. # An @ must be in the middle of the value.
  234. if '@' not in value or value.startswith('@') or value.endswith('@'):
  235. return False
  236. try:
  237. p1, p2 = value.split('@')
  238. except ValueError:
  239. # value contains more than one @.
  240. return False
  241. # Dot must be in p2 (e.g. example.com)
  242. if '.' not in p2 or p2.startswith('.'):
  243. return False
  244. return True
  245. words = word_split_re.split(str(text))
  246. for i, word in enumerate(words):
  247. if '.' in word or '@' in word or ':' in word:
  248. # lead: Current punctuation trimmed from the beginning of the word.
  249. # middle: Current state of the word.
  250. # trail: Current punctuation trimmed from the end of the word.
  251. lead, middle, trail = '', word, ''
  252. # Deal with punctuation.
  253. lead, middle, trail = trim_punctuation(lead, middle, trail)
  254. # Make URL we want to point to.
  255. url = None
  256. nofollow_attr = ' rel="nofollow"' if nofollow else ''
  257. if simple_url_re.match(middle):
  258. url = smart_urlquote(html.unescape(middle))
  259. elif simple_url_2_re.match(middle):
  260. url = smart_urlquote('http://%s' % html.unescape(middle))
  261. elif ':' not in middle and is_email_simple(middle):
  262. local, domain = middle.rsplit('@', 1)
  263. try:
  264. domain = punycode(domain)
  265. except UnicodeError:
  266. continue
  267. url = 'mailto:%s@%s' % (local, domain)
  268. nofollow_attr = ''
  269. # Make link.
  270. if url:
  271. trimmed = trim_url(middle)
  272. if autoescape and not safe_input:
  273. lead, trail = escape(lead), escape(trail)
  274. trimmed = escape(trimmed)
  275. middle = '<a href="%s"%s>%s</a>' % (escape(url), nofollow_attr, trimmed)
  276. words[i] = mark_safe('%s%s%s' % (lead, middle, trail))
  277. else:
  278. if safe_input:
  279. words[i] = mark_safe(word)
  280. elif autoescape:
  281. words[i] = escape(word)
  282. elif safe_input:
  283. words[i] = mark_safe(word)
  284. elif autoescape:
  285. words[i] = escape(word)
  286. return ''.join(words)
  287. def avoid_wrapping(value):
  288. """
  289. Avoid text wrapping in the middle of a phrase by adding non-breaking
  290. spaces where there previously were normal spaces.
  291. """
  292. return value.replace(" ", "\xa0")
  293. def html_safe(klass):
  294. """
  295. A decorator that defines the __html__ method. This helps non-Django
  296. templates to detect classes whose __str__ methods return SafeString.
  297. """
  298. if '__html__' in klass.__dict__:
  299. raise ValueError(
  300. "can't apply @html_safe to %s because it defines "
  301. "__html__()." % klass.__name__
  302. )
  303. if '__str__' not in klass.__dict__:
  304. raise ValueError(
  305. "can't apply @html_safe to %s because it doesn't "
  306. "define __str__()." % klass.__name__
  307. )
  308. klass_str = klass.__str__
  309. klass.__str__ = lambda self: mark_safe(klass_str(self))
  310. klass.__html__ = lambda self: str(self)
  311. return klass