You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

html.py 13KB

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