Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

html.py 14KB

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