html.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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 parse_qsl, quote, unquote, urlencode, urlsplit, urlunsplit
  7. from django.core.exceptions import SuspiciousOperation
  8. from django.utils.encoding import punycode
  9. from django.utils.functional import Promise, cached_property, keep_lazy, keep_lazy_text
  10. from django.utils.http import MAX_URL_LENGTH, RFC3986_GENDELIMS, RFC3986_SUBDELIMS
  11. from django.utils.regex_helper import _lazy_re_compile
  12. from django.utils.safestring import SafeData, SafeString, mark_safe
  13. from django.utils.text import normalize_newlines
  14. MAX_STRIP_TAGS_DEPTH = 50
  15. # HTML tag that opens but has no closing ">" after 1k+ chars.
  16. long_open_tag_without_closing_re = _lazy_re_compile(r"<[a-zA-Z][^>]{1000,}")
  17. @keep_lazy(SafeString)
  18. def escape(text):
  19. """
  20. Return the given text with ampersands, quotes and angle brackets encoded
  21. for use in HTML.
  22. Always escape input, even if it's already escaped and marked as such.
  23. This may result in double-escaping. If this is a concern, use
  24. conditional_escape() instead.
  25. """
  26. return SafeString(html.escape(str(text)))
  27. _js_escapes = {
  28. ord("\\"): "\\u005C",
  29. ord("'"): "\\u0027",
  30. ord('"'): "\\u0022",
  31. ord(">"): "\\u003E",
  32. ord("<"): "\\u003C",
  33. ord("&"): "\\u0026",
  34. ord("="): "\\u003D",
  35. ord("-"): "\\u002D",
  36. ord(";"): "\\u003B",
  37. ord("`"): "\\u0060",
  38. ord("\u2028"): "\\u2028",
  39. ord("\u2029"): "\\u2029",
  40. }
  41. # Escape every ASCII character with a value less than 32.
  42. _js_escapes.update((ord("%c" % z), "\\u%04X" % z) for z in range(32))
  43. @keep_lazy(SafeString)
  44. def escapejs(value):
  45. """Hex encode characters for use in JavaScript strings."""
  46. return mark_safe(str(value).translate(_js_escapes))
  47. _json_script_escapes = {
  48. ord(">"): "\\u003E",
  49. ord("<"): "\\u003C",
  50. ord("&"): "\\u0026",
  51. }
  52. def json_script(value, element_id=None, encoder=None):
  53. """
  54. Escape all the HTML/XML special characters with their unicode escapes, so
  55. value is safe to be output anywhere except for inside a tag attribute. Wrap
  56. the escaped JSON in a script tag.
  57. """
  58. from django.core.serializers.json import DjangoJSONEncoder
  59. json_str = json.dumps(value, cls=encoder or DjangoJSONEncoder).translate(
  60. _json_script_escapes
  61. )
  62. if element_id:
  63. template = '<script id="{}" type="application/json">{}</script>'
  64. args = (element_id, mark_safe(json_str))
  65. else:
  66. template = '<script type="application/json">{}</script>'
  67. args = (mark_safe(json_str),)
  68. return format_html(template, *args)
  69. def conditional_escape(text):
  70. """
  71. Similar to escape(), except that it doesn't operate on pre-escaped strings.
  72. This function relies on the __html__ convention used both by Django's
  73. SafeData class and by third-party libraries like markupsafe.
  74. """
  75. if isinstance(text, Promise):
  76. text = str(text)
  77. if hasattr(text, "__html__"):
  78. return text.__html__()
  79. else:
  80. return escape(text)
  81. def format_html(format_string, *args, **kwargs):
  82. """
  83. Similar to str.format, but pass all arguments through conditional_escape(),
  84. and call mark_safe() on the result. This function should be used instead
  85. of str.format or % interpolation to build up small HTML fragments.
  86. """
  87. args_safe = map(conditional_escape, args)
  88. kwargs_safe = {k: conditional_escape(v) for (k, v) in kwargs.items()}
  89. return mark_safe(format_string.format(*args_safe, **kwargs_safe))
  90. def format_html_join(sep, format_string, args_generator):
  91. """
  92. A wrapper of format_html, for the common case of a group of arguments that
  93. need to be formatted using the same format string, and then joined using
  94. 'sep'. 'sep' is also passed through conditional_escape.
  95. 'args_generator' should be an iterator that returns the sequence of 'args'
  96. that will be passed to format_html.
  97. Example:
  98. format_html_join('\n', "<li>{} {}</li>", ((u.first_name, u.last_name)
  99. for u in users))
  100. """
  101. return mark_safe(
  102. conditional_escape(sep).join(
  103. format_html(format_string, *args) for args in args_generator
  104. )
  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. value = str(value)
  141. for long_open_tag in long_open_tag_without_closing_re.finditer(value):
  142. if long_open_tag.group().count("<") >= MAX_STRIP_TAGS_DEPTH:
  143. raise SuspiciousOperation
  144. # Note: in typical case this loop executes _strip_once twice (the second
  145. # execution does not remove any more tags).
  146. strip_tags_depth = 0
  147. while "<" in value and ">" in value:
  148. if strip_tags_depth >= MAX_STRIP_TAGS_DEPTH:
  149. raise SuspiciousOperation
  150. new_value = _strip_once(value)
  151. if value.count("<") == new_value.count("<"):
  152. # _strip_once wasn't able to detect more tags.
  153. break
  154. value = new_value
  155. strip_tags_depth += 1
  156. return value
  157. @keep_lazy_text
  158. def strip_spaces_between_tags(value):
  159. """Return the given HTML with spaces between tags removed."""
  160. return re.sub(r">\s+<", "><", str(value))
  161. def smart_urlquote(url):
  162. """Quote a URL if it isn't already quoted."""
  163. def unquote_quote(segment):
  164. segment = unquote(segment)
  165. # Tilde is part of RFC 3986 Section 2.3 Unreserved Characters,
  166. # see also https://bugs.python.org/issue16285
  167. return quote(segment, safe=RFC3986_SUBDELIMS + RFC3986_GENDELIMS + "~")
  168. # Handle IDN before quoting.
  169. try:
  170. scheme, netloc, path, query, fragment = urlsplit(url)
  171. except ValueError:
  172. # invalid IPv6 URL (normally square brackets in hostname part).
  173. return unquote_quote(url)
  174. try:
  175. netloc = punycode(netloc) # IDN -> ACE
  176. except UnicodeError: # invalid domain part
  177. return unquote_quote(url)
  178. if query:
  179. # Separately unquoting key/value, so as to not mix querystring separators
  180. # included in query values. See #22267.
  181. query_parts = [
  182. (unquote(q[0]), unquote(q[1]))
  183. for q in parse_qsl(query, keep_blank_values=True)
  184. ]
  185. # urlencode will take care of quoting
  186. query = urlencode(query_parts)
  187. path = unquote_quote(path)
  188. fragment = unquote_quote(fragment)
  189. return urlunsplit((scheme, netloc, path, query, fragment))
  190. class CountsDict(dict):
  191. def __init__(self, *args, word, **kwargs):
  192. super().__init__(*args, *kwargs)
  193. self.word = word
  194. def __missing__(self, key):
  195. self[key] = self.word.count(key)
  196. return self[key]
  197. class Urlizer:
  198. """
  199. Convert any URLs in text into clickable links.
  200. Work on http://, https://, www. links, and also on links ending in one of
  201. the original seven gTLDs (.com, .edu, .gov, .int, .mil, .net, and .org).
  202. Links can have trailing punctuation (periods, commas, close-parens) and
  203. leading punctuation (opening parens) and it'll still do the right thing.
  204. """
  205. trailing_punctuation_chars = ".,:;!"
  206. wrapping_punctuation = [("(", ")"), ("[", "]")]
  207. simple_url_re = _lazy_re_compile(r"^https?://\[?\w", re.IGNORECASE)
  208. simple_url_2_re = _lazy_re_compile(
  209. r"^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)($|/.*)$", re.IGNORECASE
  210. )
  211. word_split_re = _lazy_re_compile(r"""([\s<>"']+)""")
  212. mailto_template = "mailto:{local}@{domain}"
  213. url_template = '<a href="{href}"{attrs}>{url}</a>'
  214. def __call__(self, text, trim_url_limit=None, nofollow=False, autoescape=False):
  215. """
  216. If trim_url_limit is not None, truncate the URLs in the link text
  217. longer than this limit to trim_url_limit - 1 characters and append an
  218. ellipsis.
  219. If nofollow is True, give the links a rel="nofollow" attribute.
  220. If autoescape is True, autoescape the link text and URLs.
  221. """
  222. safe_input = isinstance(text, SafeData)
  223. words = self.word_split_re.split(str(text))
  224. return "".join(
  225. [
  226. self.handle_word(
  227. word,
  228. safe_input=safe_input,
  229. trim_url_limit=trim_url_limit,
  230. nofollow=nofollow,
  231. autoescape=autoescape,
  232. )
  233. for word in words
  234. ]
  235. )
  236. def handle_word(
  237. self,
  238. word,
  239. *,
  240. safe_input,
  241. trim_url_limit=None,
  242. nofollow=False,
  243. autoescape=False,
  244. ):
  245. if "." in word or "@" in word or ":" in word:
  246. # lead: Punctuation trimmed from the beginning of the word.
  247. # middle: State of the word.
  248. # trail: Punctuation trimmed from the end of the word.
  249. lead, middle, trail = self.trim_punctuation(word)
  250. # Make URL we want to point to.
  251. url = None
  252. nofollow_attr = ' rel="nofollow"' if nofollow else ""
  253. if len(middle) <= MAX_URL_LENGTH and self.simple_url_re.match(middle):
  254. url = smart_urlquote(html.unescape(middle))
  255. elif len(middle) <= MAX_URL_LENGTH and self.simple_url_2_re.match(middle):
  256. url = smart_urlquote("http://%s" % html.unescape(middle))
  257. elif ":" not in middle and self.is_email_simple(middle):
  258. local, domain = middle.rsplit("@", 1)
  259. try:
  260. domain = punycode(domain)
  261. except UnicodeError:
  262. return word
  263. url = self.mailto_template.format(local=local, domain=domain)
  264. nofollow_attr = ""
  265. # Make link.
  266. if url:
  267. trimmed = self.trim_url(middle, limit=trim_url_limit)
  268. if autoescape and not safe_input:
  269. lead, trail = escape(lead), escape(trail)
  270. trimmed = escape(trimmed)
  271. middle = self.url_template.format(
  272. href=escape(url),
  273. attrs=nofollow_attr,
  274. url=trimmed,
  275. )
  276. return mark_safe(f"{lead}{middle}{trail}")
  277. else:
  278. if safe_input:
  279. return mark_safe(word)
  280. elif autoescape:
  281. return escape(word)
  282. elif safe_input:
  283. return mark_safe(word)
  284. elif autoescape:
  285. return escape(word)
  286. return word
  287. def trim_url(self, x, *, limit):
  288. if limit is None or len(x) <= limit:
  289. return x
  290. return "%s…" % x[: max(0, limit - 1)]
  291. @cached_property
  292. def wrapping_punctuation_openings(self):
  293. return "".join(dict(self.wrapping_punctuation).keys())
  294. @cached_property
  295. def trailing_punctuation_chars_no_semicolon(self):
  296. return self.trailing_punctuation_chars.replace(";", "")
  297. @cached_property
  298. def trailing_punctuation_chars_has_semicolon(self):
  299. return ";" in self.trailing_punctuation_chars
  300. def trim_punctuation(self, word):
  301. """
  302. Trim trailing and wrapping punctuation from `word`. Return the items of
  303. the new state.
  304. """
  305. # Strip all opening wrapping punctuation.
  306. middle = word.lstrip(self.wrapping_punctuation_openings)
  307. lead = word[: len(word) - len(middle)]
  308. trail = ""
  309. # Continue trimming until middle remains unchanged.
  310. trimmed_something = True
  311. counts = CountsDict(word=middle)
  312. while trimmed_something and middle:
  313. trimmed_something = False
  314. # Trim wrapping punctuation.
  315. for opening, closing in self.wrapping_punctuation:
  316. if counts[opening] < counts[closing]:
  317. rstripped = middle.rstrip(closing)
  318. if rstripped != middle:
  319. strip = counts[closing] - counts[opening]
  320. trail = middle[-strip:]
  321. middle = middle[:-strip]
  322. trimmed_something = True
  323. counts[closing] -= strip
  324. amp = middle.rfind("&")
  325. if amp == -1:
  326. rstripped = middle.rstrip(self.trailing_punctuation_chars)
  327. else:
  328. rstripped = middle.rstrip(self.trailing_punctuation_chars_no_semicolon)
  329. if rstripped != middle:
  330. trail = middle[len(rstripped) :] + trail
  331. middle = rstripped
  332. trimmed_something = True
  333. if self.trailing_punctuation_chars_has_semicolon and middle.endswith(";"):
  334. # Only strip if not part of an HTML entity.
  335. potential_entity = middle[amp:]
  336. escaped = html.unescape(potential_entity)
  337. if escaped == potential_entity or escaped.endswith(";"):
  338. rstripped = middle.rstrip(self.trailing_punctuation_chars)
  339. trail_start = len(rstripped)
  340. amount_trailing_semicolons = len(middle) - len(middle.rstrip(";"))
  341. if amp > -1 and amount_trailing_semicolons > 1:
  342. # Leave up to most recent semicolon as might be an entity.
  343. recent_semicolon = middle[trail_start:].index(";")
  344. middle_semicolon_index = recent_semicolon + trail_start + 1
  345. trail = middle[middle_semicolon_index:] + trail
  346. middle = rstripped + middle[trail_start:middle_semicolon_index]
  347. else:
  348. trail = middle[trail_start:] + trail
  349. middle = rstripped
  350. trimmed_something = True
  351. return lead, middle, trail
  352. @staticmethod
  353. def is_email_simple(value):
  354. """Return True if value looks like an email address."""
  355. # An @ must be in the middle of the value.
  356. if "@" not in value or value.startswith("@") or value.endswith("@"):
  357. return False
  358. try:
  359. p1, p2 = value.split("@")
  360. except ValueError:
  361. # value contains more than one @.
  362. return False
  363. # Max length for domain name labels is 63 characters per RFC 1034.
  364. # Helps to avoid ReDoS vectors in the domain part.
  365. if len(p2) > 63:
  366. return False
  367. # Dot must be in p2 (e.g. example.com)
  368. if "." not in p2 or p2.startswith("."):
  369. return False
  370. return True
  371. urlizer = Urlizer()
  372. @keep_lazy_text
  373. def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
  374. return urlizer(
  375. text, trim_url_limit=trim_url_limit, nofollow=nofollow, autoescape=autoescape
  376. )
  377. def avoid_wrapping(value):
  378. """
  379. Avoid text wrapping in the middle of a phrase by adding non-breaking
  380. spaces where there previously were normal spaces.
  381. """
  382. return value.replace(" ", "\xa0")
  383. def html_safe(klass):
  384. """
  385. A decorator that defines the __html__ method. This helps non-Django
  386. templates to detect classes whose __str__ methods return SafeString.
  387. """
  388. if "__html__" in klass.__dict__:
  389. raise ValueError(
  390. "can't apply @html_safe to %s because it defines "
  391. "__html__()." % klass.__name__
  392. )
  393. if "__str__" not in klass.__dict__:
  394. raise ValueError(
  395. "can't apply @html_safe to %s because it doesn't "
  396. "define __str__()." % klass.__name__
  397. )
  398. klass_str = klass.__str__
  399. klass.__str__ = lambda self: mark_safe(klass_str(self))
  400. klass.__html__ = lambda self: str(self)
  401. return klass