html.py 15 KB

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