html.py 17 KB

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