html.py 17 KB

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