PageRenderTime 90ms CodeModel.GetById 42ms RepoModel.GetById 18ms app.codeStats 0ms

/django/utils/html.py

https://github.com/sesostris/django
Python | 278 lines | 245 code | 15 blank | 18 comment | 11 complexity | 3d7a5fb0ed7a0db98760691ba9efd55f MD5 | raw file
Possible License(s): BSD-3-Clause
  1. """HTML utilities suitable for global use."""
  2. from __future__ import unicode_literals
  3. import re
  4. import string
  5. try:
  6. from urllib.parse import quote, urlsplit, urlunsplit
  7. except ImportError: # Python 2
  8. from urllib import quote
  9. from urlparse import urlsplit, urlunsplit
  10. from django.utils.safestring import SafeData, mark_safe
  11. from django.utils.encoding import force_bytes, force_text
  12. from django.utils.functional import allow_lazy
  13. from django.utils import six
  14. from django.utils.text import normalize_newlines
  15. # Configuration for urlize() function.
  16. TRAILING_PUNCTUATION = ['.', ',', ':', ';', '.)']
  17. WRAPPING_PUNCTUATION = [('(', ')'), ('<', '>'), ('&lt;', '&gt;')]
  18. # List of possible strings used for bullets in bulleted lists.
  19. DOTS = ['&middot;', '*', '\u2022', '&#149;', '&bull;', '&#8226;']
  20. unencoded_ampersands_re = re.compile(r'&(?!(\w+|#\d+);)')
  21. unquoted_percents_re = re.compile(r'%(?![0-9A-Fa-f]{2})')
  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(r'(?:<br clear="all">|<i><\/i>|<b><\/b>|<em><\/em>|<strong><\/strong>|<\/?smallcaps>|<\/?uppercase>)', re.IGNORECASE)
  28. hard_coded_bullets_re = re.compile(r'((?:<p>(?:%s).*?[a-zA-Z].*?</p>\s*)+)' % '|'.join([re.escape(x) for x in DOTS]), re.DOTALL)
  29. trailing_empty_content_re = re.compile(r'(?:<p>(?:&nbsp;|\s|<br \/>)*?</p>\s*)+\Z')
  30. def escape(text):
  31. """
  32. Returns the given text with ampersands, quotes and angle brackets encoded for use in HTML.
  33. """
  34. return mark_safe(force_text(text).replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;'))
  35. escape = allow_lazy(escape, six.text_type)
  36. _base_js_escapes = (
  37. ('\\', '\\u005C'),
  38. ('\'', '\\u0027'),
  39. ('"', '\\u0022'),
  40. ('>', '\\u003E'),
  41. ('<', '\\u003C'),
  42. ('&', '\\u0026'),
  43. ('=', '\\u003D'),
  44. ('-', '\\u002D'),
  45. (';', '\\u003B'),
  46. ('\u2028', '\\u2028'),
  47. ('\u2029', '\\u2029')
  48. )
  49. # Escape every ASCII character with a value less than 32.
  50. _js_escapes = (_base_js_escapes +
  51. tuple([('%c' % z, '\\u%04X' % z) for z in range(32)]))
  52. def escapejs(value):
  53. """Hex encodes characters for use in JavaScript strings."""
  54. for bad, good in _js_escapes:
  55. value = mark_safe(force_text(value).replace(bad, good))
  56. return value
  57. escapejs = allow_lazy(escapejs, six.text_type)
  58. def conditional_escape(text):
  59. """
  60. Similar to escape(), except that it doesn't operate on pre-escaped strings.
  61. """
  62. if isinstance(text, SafeData):
  63. return text
  64. else:
  65. return escape(text)
  66. def format_html(format_string, *args, **kwargs):
  67. """
  68. Similar to str.format, but passes all arguments through conditional_escape,
  69. and calls '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 = dict([(k, conditional_escape(v)) for (k, v) in
  74. six.iteritems(kwargs)])
  75. return mark_safe(format_string.format(*args_safe, **kwargs_safe))
  76. def format_html_join(sep, format_string, args_generator):
  77. """
  78. A wrapper format_html, for the common case of a group of arguments that need
  79. to be formatted using the same format string, and then joined using
  80. 'sep'. 'sep' is also passed through conditional_escape.
  81. 'args_generator' should be an iterator that returns the sequence of 'args'
  82. that will be passed to format_html.
  83. Example:
  84. format_html_join('\n', "<li>{0} {1}</li>", ((u.first_name, u.last_name)
  85. for u in users))
  86. """
  87. return mark_safe(conditional_escape(sep).join(
  88. format_html(format_string, *tuple(args))
  89. for args in args_generator))
  90. def linebreaks(value, autoescape=False):
  91. """Converts newlines into <p> and <br />s."""
  92. value = normalize_newlines(value)
  93. paras = re.split('\n{2,}', 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. linebreaks = allow_lazy(linebreaks, six.text_type)
  100. def strip_tags(value):
  101. """Returns the given HTML with all tags stripped."""
  102. return re.sub(r'<[^>]*?>', '', force_text(value))
  103. strip_tags = allow_lazy(strip_tags)
  104. def remove_tags(html, tags):
  105. """Returns the given HTML with given tags removed."""
  106. tags = [re.escape(tag) for tag in tags.split()]
  107. tags_re = '(%s)' % '|'.join(tags)
  108. starttag_re = re.compile(r'<%s(/?>|(\s+[^>]*>))' % tags_re, re.U)
  109. endtag_re = re.compile('</%s>' % tags_re)
  110. html = starttag_re.sub('', html)
  111. html = endtag_re.sub('', html)
  112. return html
  113. remove_tags = allow_lazy(remove_tags, six.text_type)
  114. def strip_spaces_between_tags(value):
  115. """Returns the given HTML with spaces between tags removed."""
  116. return re.sub(r'>\s+<', '><', force_text(value))
  117. strip_spaces_between_tags = allow_lazy(strip_spaces_between_tags, six.text_type)
  118. def strip_entities(value):
  119. """Returns the given HTML with all entities (&something;) stripped."""
  120. return re.sub(r'&(?:\w+|#\d+);', '', force_text(value))
  121. strip_entities = allow_lazy(strip_entities, six.text_type)
  122. def fix_ampersands(value):
  123. """Returns the given HTML with all unencoded ampersands encoded correctly."""
  124. return unencoded_ampersands_re.sub('&amp;', force_text(value))
  125. fix_ampersands = allow_lazy(fix_ampersands, six.text_type)
  126. def smart_urlquote(url):
  127. "Quotes a URL if it isn't already quoted."
  128. # Handle IDN before quoting.
  129. scheme, netloc, path, query, fragment = urlsplit(url)
  130. try:
  131. netloc = netloc.encode('idna').decode('ascii') # IDN -> ACE
  132. except UnicodeError: # invalid domain part
  133. pass
  134. else:
  135. url = urlunsplit((scheme, netloc, path, query, fragment))
  136. # An URL is considered unquoted if it contains no % characters or
  137. # contains a % not followed by two hexadecimal digits. See #9655.
  138. if '%' not in url or unquoted_percents_re.search(url):
  139. # See http://bugs.python.org/issue2637
  140. url = quote(force_bytes(url), safe=b'!*\'();:@&=+$,/?#[]~')
  141. return force_text(url)
  142. def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
  143. """
  144. Converts any URLs in text into clickable links.
  145. Works on http://, https://, www. links, and also on links ending in one of
  146. the original seven gTLDs (.com, .edu, .gov, .int, .mil, .net, and .org).
  147. Links can have trailing punctuation (periods, commas, close-parens) and
  148. leading punctuation (opening parens) and it'll still do the right thing.
  149. If trim_url_limit is not None, the URLs in link text longer than this limit
  150. will truncated to trim_url_limit-3 characters and appended with an elipsis.
  151. If nofollow is True, the URLs in link text will get a rel="nofollow"
  152. attribute.
  153. If autoescape is True, the link text and URLs will get autoescaped.
  154. """
  155. trim_url = lambda x, limit=trim_url_limit: limit is not None and (len(x) > limit and ('%s...' % x[:max(0, limit - 3)])) or x
  156. safe_input = isinstance(text, SafeData)
  157. words = word_split_re.split(force_text(text))
  158. for i, word in enumerate(words):
  159. match = None
  160. if '.' in word or '@' in word or ':' in word:
  161. # Deal with punctuation.
  162. lead, middle, trail = '', word, ''
  163. for punctuation in TRAILING_PUNCTUATION:
  164. if middle.endswith(punctuation):
  165. middle = middle[:-len(punctuation)]
  166. trail = punctuation + trail
  167. for opening, closing in WRAPPING_PUNCTUATION:
  168. if middle.startswith(opening):
  169. middle = middle[len(opening):]
  170. lead = lead + opening
  171. # Keep parentheses at the end only if they're balanced.
  172. if (middle.endswith(closing)
  173. and middle.count(closing) == middle.count(opening) + 1):
  174. middle = middle[:-len(closing)]
  175. trail = closing + trail
  176. # Make URL we want to point to.
  177. url = None
  178. nofollow_attr = ' rel="nofollow"' if nofollow else ''
  179. if simple_url_re.match(middle):
  180. url = smart_urlquote(middle)
  181. elif simple_url_2_re.match(middle):
  182. url = smart_urlquote('http://%s' % middle)
  183. elif not ':' in middle and simple_email_re.match(middle):
  184. local, domain = middle.rsplit('@', 1)
  185. try:
  186. domain = domain.encode('idna').decode('ascii')
  187. except UnicodeError:
  188. continue
  189. url = 'mailto:%s@%s' % (local, domain)
  190. nofollow_attr = ''
  191. # Make link.
  192. if url:
  193. trimmed = trim_url(middle)
  194. if autoescape and not safe_input:
  195. lead, trail = escape(lead), escape(trail)
  196. url, trimmed = escape(url), escape(trimmed)
  197. middle = '<a href="%s"%s>%s</a>' % (url, nofollow_attr, trimmed)
  198. words[i] = mark_safe('%s%s%s' % (lead, middle, trail))
  199. else:
  200. if safe_input:
  201. words[i] = mark_safe(word)
  202. elif autoescape:
  203. words[i] = escape(word)
  204. elif safe_input:
  205. words[i] = mark_safe(word)
  206. elif autoescape:
  207. words[i] = escape(word)
  208. return ''.join(words)
  209. urlize = allow_lazy(urlize, six.text_type)
  210. def clean_html(text):
  211. """
  212. Clean the given HTML. Specifically, do the following:
  213. * Convert <b> and <i> to <strong> and <em>.
  214. * Encode all ampersands correctly.
  215. * Remove all "target" attributes from <a> tags.
  216. * Remove extraneous HTML, such as presentational tags that open and
  217. immediately close and <br clear="all">.
  218. * Convert hard-coded bullets into HTML unordered lists.
  219. * Remove stuff like "<p>&nbsp;&nbsp;</p>", but only if it's at the
  220. bottom of the text.
  221. """
  222. from django.utils.text import normalize_newlines
  223. text = normalize_newlines(force_text(text))
  224. text = re.sub(r'<(/?)\s*b\s*>', '<\\1strong>', text)
  225. text = re.sub(r'<(/?)\s*i\s*>', '<\\1em>', text)
  226. text = fix_ampersands(text)
  227. # Remove all target="" attributes from <a> tags.
  228. text = link_target_attribute_re.sub('\\1', text)
  229. # Trim stupid HTML such as <br clear="all">.
  230. text = html_gunk_re.sub('', text)
  231. # Convert hard-coded bullets into HTML unordered lists.
  232. def replace_p_tags(match):
  233. s = match.group().replace('</p>', '</li>')
  234. for d in DOTS:
  235. s = s.replace('<p>%s' % d, '<li>')
  236. return '<ul>\n%s\n</ul>' % s
  237. text = hard_coded_bullets_re.sub(replace_p_tags, text)
  238. # Remove stuff like "<p>&nbsp;&nbsp;</p>", but only if it's at the bottom
  239. # of the text.
  240. text = trailing_empty_content_re.sub('', text)
  241. return text
  242. clean_html = allow_lazy(clean_html, six.text_type)