html.py 18 KB

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