html.py 14 KB

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