html.py 13 KB

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