Development of an internal social media platform with personalised dashboards for students
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 13KB

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