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 14 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. """HTML utilities suitable for global use."""
  2. from __future__ import unicode_literals
  3. import re
  4. import warnings
  5. from django.utils import six
  6. from django.utils.deprecation import RemovedInDjango110Warning
  7. from django.utils.encoding import force_str, force_text
  8. from django.utils.functional import allow_lazy
  9. from django.utils.http import RFC3986_GENDELIMS, RFC3986_SUBDELIMS
  10. from django.utils.safestring import SafeData, SafeText, mark_safe
  11. from django.utils.six.moves.urllib.parse import (
  12. parse_qsl, quote, unquote, urlencode, urlsplit, urlunsplit,
  13. )
  14. from django.utils.text import normalize_newlines
  15. from .html_parser import HTMLParseError, HTMLParser
  16. # Configuration for urlize() function.
  17. TRAILING_PUNCTUATION = ['.', ',', ':', ';', '.)', '"', '\'', '!']
  18. WRAPPING_PUNCTUATION = [('(', ')'), ('<', '>'), ('[', ']'), ('&lt;', '&gt;'), ('"', '"'), ('\'', '\'')]
  19. # List of possible strings used for bullets in bulleted lists.
  20. DOTS = ['&middot;', '*', '\u2022', '&#149;', '&bull;', '&#8226;']
  21. unencoded_ampersands_re = re.compile(r'&(?!(\w+|#\d+);)')
  22. word_split_re = re.compile(r'''([\s<>"']+)''')
  23. simple_url_re = re.compile(r'^https?://\[?\w', re.IGNORECASE)
  24. simple_url_2_re = re.compile(r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)($|/.*)$', re.IGNORECASE)
  25. simple_email_re = re.compile(r'^\S+@\S+\.\S+$')
  26. link_target_attribute_re = re.compile(r'(<a [^>]*?)target=[^\s>]+')
  27. html_gunk_re = re.compile(
  28. r'(?:<br clear="all">|<i><\/i>|<b><\/b>|<em><\/em>|<strong><\/strong>|'
  29. '<\/?smallcaps>|<\/?uppercase>)', re.IGNORECASE)
  30. hard_coded_bullets_re = re.compile(
  31. r'((?:<p>(?:%s).*?[a-zA-Z].*?</p>\s*)+)' % '|'.join(re.escape(x)
  32. for x in DOTS), re.DOTALL)
  33. trailing_empty_content_re = re.compile(r'(?:<p>(?:&nbsp;|\s|<br \/>)*?</p>\s*)+\Z')
  34. def escape(text):
  35. """
  36. Returns the given text with ampersands, quotes and angle brackets encoded
  37. for use in HTML.
  38. This function always escapes its input, even if it's already escaped and
  39. marked as such. This may result in double-escaping. If this is a concern,
  40. use conditional_escape() instead.
  41. """
  42. return mark_safe(force_text(text).replace('&', '&amp;').replace('<', '&lt;')
  43. .replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;'))
  44. escape = allow_lazy(escape, six.text_type, SafeText)
  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('\u2028'): '\\u2028',
  56. ord('\u2029'): '\\u2029'
  57. }
  58. # Escape every ASCII character with a value less than 32.
  59. _js_escapes.update((ord('%c' % z), '\\u%04X' % z) for z in range(32))
  60. def escapejs(value):
  61. """Hex encodes characters for use in JavaScript strings."""
  62. return mark_safe(force_text(value).translate(_js_escapes))
  63. escapejs = allow_lazy(escapejs, six.text_type, SafeText)
  64. def conditional_escape(text):
  65. """
  66. Similar to escape(), except that it doesn't operate on pre-escaped strings.
  67. This function relies on the __html__ convention used both by Django's
  68. SafeData class and by third-party libraries like markupsafe.
  69. """
  70. if hasattr(text, '__html__'):
  71. return text.__html__()
  72. else:
  73. return escape(text)
  74. def format_html(format_string, *args, **kwargs):
  75. """
  76. Similar to str.format, but passes all arguments through conditional_escape,
  77. and calls 'mark_safe' on the result. This function should be used instead
  78. of str.format or % interpolation to build up small HTML fragments.
  79. """
  80. args_safe = map(conditional_escape, args)
  81. kwargs_safe = {k: conditional_escape(v) for (k, v) in six.iteritems(kwargs)}
  82. return mark_safe(format_string.format(*args_safe, **kwargs_safe))
  83. def format_html_join(sep, format_string, args_generator):
  84. """
  85. A wrapper of format_html, for the common case of a group of arguments that
  86. need to be formatted using the same format string, and then joined using
  87. 'sep'. 'sep' is also passed through conditional_escape.
  88. 'args_generator' should be an iterator that returns the sequence of 'args'
  89. that will be passed to format_html.
  90. Example:
  91. format_html_join('\n', "<li>{} {}</li>", ((u.first_name, u.last_name)
  92. for u in users))
  93. """
  94. return mark_safe(conditional_escape(sep).join(
  95. format_html(format_string, *tuple(args))
  96. for args in args_generator))
  97. def linebreaks(value, autoescape=False):
  98. """Converts newlines into <p> and <br />s."""
  99. value = normalize_newlines(value)
  100. paras = re.split('\n{2,}', value)
  101. if autoescape:
  102. paras = ['<p>%s</p>' % escape(p).replace('\n', '<br />') for p in paras]
  103. else:
  104. paras = ['<p>%s</p>' % p.replace('\n', '<br />') for p in paras]
  105. return '\n\n'.join(paras)
  106. linebreaks = allow_lazy(linebreaks, six.text_type)
  107. class MLStripper(HTMLParser):
  108. def __init__(self):
  109. HTMLParser.__init__(self)
  110. self.reset()
  111. self.fed = []
  112. def handle_data(self, d):
  113. self.fed.append(d)
  114. def handle_entityref(self, name):
  115. self.fed.append('&%s;' % name)
  116. def handle_charref(self, name):
  117. self.fed.append('&#%s;' % name)
  118. def get_data(self):
  119. return ''.join(self.fed)
  120. def _strip_once(value):
  121. """
  122. Internal tag stripping utility used by strip_tags.
  123. """
  124. s = MLStripper()
  125. try:
  126. s.feed(value)
  127. except HTMLParseError:
  128. return value
  129. try:
  130. s.close()
  131. except HTMLParseError:
  132. return s.get_data() + s.rawdata
  133. else:
  134. return s.get_data()
  135. def strip_tags(value):
  136. """Returns the given HTML with all tags stripped."""
  137. # Note: in typical case this loop executes _strip_once once. Loop condition
  138. # is redundant, but helps to reduce number of executions of _strip_once.
  139. while '<' in value and '>' in value:
  140. new_value = _strip_once(value)
  141. if len(new_value) >= len(value):
  142. # _strip_once was not able to detect more tags or length increased
  143. # due to http://bugs.python.org/issue20288
  144. # (affects Python 2 < 2.7.7 and Python 3 < 3.3.5)
  145. break
  146. value = new_value
  147. return value
  148. strip_tags = allow_lazy(strip_tags)
  149. def remove_tags(html, tags):
  150. """Returns the given HTML with given tags removed."""
  151. warnings.warn(
  152. "django.utils.html.remove_tags() and the removetags template filter "
  153. "are deprecated. Consider using the bleach library instead.",
  154. RemovedInDjango110Warning, stacklevel=3
  155. )
  156. tags = [re.escape(tag) for tag in tags.split()]
  157. tags_re = '(%s)' % '|'.join(tags)
  158. starttag_re = re.compile(r'<%s(/?>|(\s+[^>]*>))' % tags_re, re.U)
  159. endtag_re = re.compile('</%s>' % tags_re)
  160. html = starttag_re.sub('', html)
  161. html = endtag_re.sub('', html)
  162. return html
  163. remove_tags = allow_lazy(remove_tags, six.text_type)
  164. def strip_spaces_between_tags(value):
  165. """Returns the given HTML with spaces between tags removed."""
  166. return re.sub(r'>\s+<', '><', force_text(value))
  167. strip_spaces_between_tags = allow_lazy(strip_spaces_between_tags, six.text_type)
  168. def strip_entities(value):
  169. """Returns the given HTML with all entities (&something;) stripped."""
  170. warnings.warn(
  171. "django.utils.html.strip_entities() is deprecated.",
  172. RemovedInDjango110Warning, stacklevel=2
  173. )
  174. return re.sub(r'&(?:\w+|#\d+);', '', force_text(value))
  175. strip_entities = allow_lazy(strip_entities, six.text_type)
  176. def smart_urlquote(url):
  177. "Quotes a URL if it isn't already quoted."
  178. def unquote_quote(segment):
  179. segment = unquote(force_str(segment))
  180. # Tilde is part of RFC3986 Unreserved Characters
  181. # http://tools.ietf.org/html/rfc3986#section-2.3
  182. # See also http://bugs.python.org/issue16285
  183. segment = quote(segment, safe=RFC3986_SUBDELIMS + RFC3986_GENDELIMS + str('~'))
  184. return force_text(segment)
  185. # Handle IDN before quoting.
  186. try:
  187. scheme, netloc, path, query, fragment = urlsplit(url)
  188. except ValueError:
  189. # invalid IPv6 URL (normally square brackets in hostname part).
  190. return unquote_quote(url)
  191. try:
  192. netloc = netloc.encode('idna').decode('ascii') # IDN -> ACE
  193. except UnicodeError: # invalid domain part
  194. return unquote_quote(url)
  195. if query:
  196. # Separately unquoting key/value, so as to not mix querystring separators
  197. # included in query values. See #22267.
  198. query_parts = [(unquote(force_str(q[0])), unquote(force_str(q[1])))
  199. for q in parse_qsl(query, keep_blank_values=True)]
  200. # urlencode will take care of quoting
  201. query = urlencode(query_parts)
  202. path = unquote_quote(path)
  203. fragment = unquote_quote(fragment)
  204. return urlunsplit((scheme, netloc, path, query, fragment))
  205. def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
  206. """
  207. Converts any URLs in text into clickable links.
  208. Works on http://, https://, www. links, and also on links ending in one of
  209. the original seven gTLDs (.com, .edu, .gov, .int, .mil, .net, and .org).
  210. Links can have trailing punctuation (periods, commas, close-parens) and
  211. leading punctuation (opening parens) and it'll still do the right thing.
  212. If trim_url_limit is not None, the URLs in the link text longer than this
  213. limit will be truncated to trim_url_limit-3 characters and appended with
  214. an ellipsis.
  215. If nofollow is True, the links will get a rel="nofollow" attribute.
  216. If autoescape is True, the link text and URLs will be autoescaped.
  217. """
  218. safe_input = isinstance(text, SafeData)
  219. def trim_url(x, limit=trim_url_limit):
  220. if limit is None or len(x) <= limit:
  221. return x
  222. return '%s...' % x[:max(0, limit - 3)]
  223. def unescape(text, trail):
  224. """
  225. If input URL is HTML-escaped, unescape it so as we can safely feed it to
  226. smart_urlquote. For example:
  227. http://example.com?x=1&amp;y=&lt;2&gt; => http://example.com?x=1&y=<2>
  228. """
  229. unescaped = (text + trail).replace(
  230. '&amp;', '&').replace('&lt;', '<').replace(
  231. '&gt;', '>').replace('&quot;', '"').replace('&#39;', "'")
  232. if trail and unescaped.endswith(trail):
  233. # Remove trail for unescaped if it was not consumed by unescape
  234. unescaped = unescaped[:-len(trail)]
  235. elif trail == ';':
  236. # Trail was consumed by unescape (as end-of-entity marker), move it to text
  237. text += trail
  238. trail = ''
  239. return text, unescaped, trail
  240. words = word_split_re.split(force_text(text))
  241. for i, word in enumerate(words):
  242. if '.' in word or '@' in word or ':' in word:
  243. # Deal with punctuation.
  244. lead, middle, trail = '', word, ''
  245. for punctuation in TRAILING_PUNCTUATION:
  246. if middle.endswith(punctuation):
  247. middle = middle[:-len(punctuation)]
  248. trail = punctuation + trail
  249. for opening, closing in WRAPPING_PUNCTUATION:
  250. if middle.startswith(opening):
  251. middle = middle[len(opening):]
  252. lead = lead + opening
  253. # Keep parentheses at the end only if they're balanced.
  254. if (middle.endswith(closing)
  255. and middle.count(closing) == middle.count(opening) + 1):
  256. middle = middle[:-len(closing)]
  257. trail = closing + trail
  258. # Make URL we want to point to.
  259. url = None
  260. nofollow_attr = ' rel="nofollow"' if nofollow else ''
  261. if simple_url_re.match(middle):
  262. middle, middle_unescaped, trail = unescape(middle, trail)
  263. url = smart_urlquote(middle_unescaped)
  264. elif simple_url_2_re.match(middle):
  265. middle, middle_unescaped, trail = unescape(middle, trail)
  266. url = smart_urlquote('http://%s' % middle_unescaped)
  267. elif ':' not in middle and simple_email_re.match(middle):
  268. local, domain = middle.rsplit('@', 1)
  269. try:
  270. domain = domain.encode('idna').decode('ascii')
  271. except UnicodeError:
  272. continue
  273. url = 'mailto:%s@%s' % (local, domain)
  274. nofollow_attr = ''
  275. # Make link.
  276. if url:
  277. trimmed = trim_url(middle)
  278. if autoescape and not safe_input:
  279. lead, trail = escape(lead), escape(trail)
  280. trimmed = escape(trimmed)
  281. middle = '<a href="%s"%s>%s</a>' % (escape(url), nofollow_attr, trimmed)
  282. words[i] = mark_safe('%s%s%s' % (lead, middle, trail))
  283. else:
  284. if safe_input:
  285. words[i] = mark_safe(word)
  286. elif autoescape:
  287. words[i] = escape(word)
  288. elif safe_input:
  289. words[i] = mark_safe(word)
  290. elif autoescape:
  291. words[i] = escape(word)
  292. return ''.join(words)
  293. urlize = allow_lazy(urlize, six.text_type)
  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 six.PY2:
  311. if '__unicode__' not in klass.__dict__:
  312. raise ValueError(
  313. "can't apply @html_safe to %s because it doesn't "
  314. "define __unicode__()." % klass.__name__
  315. )
  316. klass_unicode = klass.__unicode__
  317. klass.__unicode__ = lambda self: mark_safe(klass_unicode(self))
  318. klass.__html__ = lambda self: unicode(self) # NOQA: unicode undefined on PY3
  319. else:
  320. if '__str__' not in klass.__dict__:
  321. raise ValueError(
  322. "can't apply @html_safe to %s because it doesn't "
  323. "define __str__()." % klass.__name__
  324. )
  325. klass_str = klass.__str__
  326. klass.__str__ = lambda self: mark_safe(klass_str(self))
  327. klass.__html__ = lambda self: str(self)
  328. return klass