PageRenderTime 44ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/django/utils/html.py

https://github.com/andnils/django
Python | 306 lines | 271 code | 18 blank | 17 comment | 8 complexity | 0b84d9c181eb0d00f0a2376e4a666014 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 sys
  5. from django.utils.encoding import force_text, force_str
  6. from django.utils.functional import allow_lazy
  7. from django.utils.safestring import SafeData, mark_safe
  8. from django.utils import six
  9. from django.utils.six.moves.urllib.parse import quote, unquote, urlsplit, urlunsplit
  10. from django.utils.text import normalize_newlines
  11. from .html_parser import HTMLParser, HTMLParseError
  12. # Configuration for urlize() function.
  13. TRAILING_PUNCTUATION = ['.', ',', ':', ';', '.)', '"', '\'']
  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. simple_email_re = re.compile(r'^\S+@\S+\.\S+$')
  22. link_target_attribute_re = re.compile(r'(<a [^>]*?)target=[^\s>]+')
  23. html_gunk_re = re.compile(r'(?:<br clear="all">|<i><\/i>|<b><\/b>|<em><\/em>|<strong><\/strong>|<\/?smallcaps>|<\/?uppercase>)', re.IGNORECASE)
  24. hard_coded_bullets_re = re.compile(r'((?:<p>(?:%s).*?[a-zA-Z].*?</p>\s*)+)' % '|'.join(re.escape(x) for x in DOTS), re.DOTALL)
  25. trailing_empty_content_re = re.compile(r'(?:<p>(?:&nbsp;|\s|<br \/>)*?</p>\s*)+\Z')
  26. def escape(text):
  27. """
  28. Returns the given text with ampersands, quotes and angle brackets encoded for use in HTML.
  29. """
  30. return mark_safe(force_text(text).replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;'))
  31. escape = allow_lazy(escape, six.text_type)
  32. _js_escapes = {
  33. ord('\\'): '\\u005C',
  34. ord('\''): '\\u0027',
  35. ord('"'): '\\u0022',
  36. ord('>'): '\\u003E',
  37. ord('<'): '\\u003C',
  38. ord('&'): '\\u0026',
  39. ord('='): '\\u003D',
  40. ord('-'): '\\u002D',
  41. ord(';'): '\\u003B',
  42. ord('\u2028'): '\\u2028',
  43. ord('\u2029'): '\\u2029'
  44. }
  45. # Escape every ASCII character with a value less than 32.
  46. _js_escapes.update((ord('%c' % z), '\\u%04X' % z) for z in range(32))
  47. def escapejs(value):
  48. """Hex encodes characters for use in JavaScript strings."""
  49. return mark_safe(force_text(value).translate(_js_escapes))
  50. escapejs = allow_lazy(escapejs, six.text_type)
  51. def conditional_escape(text):
  52. """
  53. Similar to escape(), except that it doesn't operate on pre-escaped strings.
  54. """
  55. if hasattr(text, '__html__'):
  56. return text.__html__()
  57. else:
  58. return escape(text)
  59. def format_html(format_string, *args, **kwargs):
  60. """
  61. Similar to str.format, but passes all arguments through conditional_escape,
  62. and calls 'mark_safe' on the result. This function should be used instead
  63. of str.format or % interpolation to build up small HTML fragments.
  64. """
  65. args_safe = map(conditional_escape, args)
  66. kwargs_safe = dict((k, conditional_escape(v)) for (k, v) in six.iteritems(kwargs))
  67. return mark_safe(format_string.format(*args_safe, **kwargs_safe))
  68. def format_html_join(sep, format_string, args_generator):
  69. """
  70. A wrapper of format_html, for the common case of a group of arguments that
  71. need to be formatted using the same format string, and then joined using
  72. 'sep'. 'sep' is also passed through conditional_escape.
  73. 'args_generator' should be an iterator that returns the sequence of 'args'
  74. that will be passed to format_html.
  75. Example:
  76. format_html_join('\n', "<li>{0} {1}</li>", ((u.first_name, u.last_name)
  77. for u in users))
  78. """
  79. return mark_safe(conditional_escape(sep).join(
  80. format_html(format_string, *tuple(args))
  81. for args in args_generator))
  82. def linebreaks(value, autoescape=False):
  83. """Converts newlines into <p> and <br />s."""
  84. value = normalize_newlines(value)
  85. paras = re.split('\n{2,}', value)
  86. if autoescape:
  87. paras = ['<p>%s</p>' % escape(p).replace('\n', '<br />') for p in paras]
  88. else:
  89. paras = ['<p>%s</p>' % p.replace('\n', '<br />') for p in paras]
  90. return '\n\n'.join(paras)
  91. linebreaks = allow_lazy(linebreaks, six.text_type)
  92. class MLStripper(HTMLParser):
  93. def __init__(self):
  94. # The strict parameter was added in Python 3.2 with a default of True.
  95. # The default changed to False in Python 3.3 and was deprecated.
  96. if sys.version_info[:2] == (3, 2):
  97. HTMLParser.__init__(self, strict=False)
  98. else:
  99. HTMLParser.__init__(self)
  100. self.reset()
  101. self.fed = []
  102. def handle_data(self, d):
  103. self.fed.append(d)
  104. def handle_entityref(self, name):
  105. self.fed.append('&%s;' % name)
  106. def handle_charref(self, name):
  107. self.fed.append('&#%s;' % name)
  108. def get_data(self):
  109. return ''.join(self.fed)
  110. def _strip_once(value):
  111. """
  112. Internal tag stripping utility used by strip_tags.
  113. """
  114. s = MLStripper()
  115. try:
  116. s.feed(value)
  117. except HTMLParseError:
  118. return value
  119. try:
  120. s.close()
  121. except (HTMLParseError, UnboundLocalError):
  122. # UnboundLocalError because of http://bugs.python.org/issue17802
  123. # on Python 3.2, triggered by strict=False mode of HTMLParser
  124. return s.get_data() + s.rawdata
  125. else:
  126. return s.get_data()
  127. def strip_tags(value):
  128. """Returns the given HTML with all tags stripped."""
  129. while True:
  130. if not ('<' in value or '>' in value):
  131. return value
  132. new_value = _strip_once(value)
  133. if new_value == value:
  134. # _strip_once was not able to detect more tags
  135. return value
  136. else:
  137. value = new_value
  138. strip_tags = allow_lazy(strip_tags)
  139. def remove_tags(html, tags):
  140. """Returns the given HTML with given tags removed."""
  141. tags = [re.escape(tag) for tag in tags.split()]
  142. tags_re = '(%s)' % '|'.join(tags)
  143. starttag_re = re.compile(r'<%s(/?>|(\s+[^>]*>))' % tags_re, re.U)
  144. endtag_re = re.compile('</%s>' % tags_re)
  145. html = starttag_re.sub('', html)
  146. html = endtag_re.sub('', html)
  147. return html
  148. remove_tags = allow_lazy(remove_tags, six.text_type)
  149. def strip_spaces_between_tags(value):
  150. """Returns the given HTML with spaces between tags removed."""
  151. return re.sub(r'>\s+<', '><', force_text(value))
  152. strip_spaces_between_tags = allow_lazy(strip_spaces_between_tags, six.text_type)
  153. def strip_entities(value):
  154. """Returns the given HTML with all entities (&something;) stripped."""
  155. return re.sub(r'&(?:\w+|#\d+);', '', force_text(value))
  156. strip_entities = allow_lazy(strip_entities, six.text_type)
  157. def smart_urlquote(url):
  158. "Quotes a URL if it isn't already quoted."
  159. # Handle IDN before quoting.
  160. try:
  161. scheme, netloc, path, query, fragment = urlsplit(url)
  162. try:
  163. netloc = netloc.encode('idna').decode('ascii') # IDN -> ACE
  164. except UnicodeError: # invalid domain part
  165. pass
  166. else:
  167. url = urlunsplit((scheme, netloc, path, query, fragment))
  168. except ValueError:
  169. # invalid IPv6 URL (normally square brackets in hostname part).
  170. pass
  171. url = unquote(force_str(url))
  172. # See http://bugs.python.org/issue2637
  173. url = quote(url, safe=b'!*\'();:@&=+$,/?#[]~')
  174. return force_text(url)
  175. def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
  176. """
  177. Converts any URLs in text into clickable links.
  178. Works on http://, https://, www. links, and also on links ending in one of
  179. the original seven gTLDs (.com, .edu, .gov, .int, .mil, .net, and .org).
  180. Links can have trailing punctuation (periods, commas, close-parens) and
  181. leading punctuation (opening parens) and it'll still do the right thing.
  182. If trim_url_limit is not None, the URLs in the link text longer than this
  183. limit will be truncated to trim_url_limit-3 characters and appended with
  184. an ellipsis.
  185. If nofollow is True, the links will get a rel="nofollow" attribute.
  186. If autoescape is True, the link text and URLs will be autoescaped.
  187. """
  188. def trim_url(x, limit=trim_url_limit):
  189. if limit is None or len(x) <= limit:
  190. return x
  191. return '%s...' % x[:max(0, limit - 3)]
  192. safe_input = isinstance(text, SafeData)
  193. words = word_split_re.split(force_text(text))
  194. for i, word in enumerate(words):
  195. if '.' in word or '@' in word or ':' in word:
  196. # Deal with punctuation.
  197. lead, middle, trail = '', word, ''
  198. for punctuation in TRAILING_PUNCTUATION:
  199. if middle.endswith(punctuation):
  200. middle = middle[:-len(punctuation)]
  201. trail = punctuation + trail
  202. for opening, closing in WRAPPING_PUNCTUATION:
  203. if middle.startswith(opening):
  204. middle = middle[len(opening):]
  205. lead = lead + opening
  206. # Keep parentheses at the end only if they're balanced.
  207. if (middle.endswith(closing)
  208. and middle.count(closing) == middle.count(opening) + 1):
  209. middle = middle[:-len(closing)]
  210. trail = closing + trail
  211. # Make URL we want to point to.
  212. url = None
  213. nofollow_attr = ' rel="nofollow"' if nofollow else ''
  214. if simple_url_re.match(middle):
  215. url = smart_urlquote(middle)
  216. elif simple_url_2_re.match(middle):
  217. url = smart_urlquote('http://%s' % middle)
  218. elif not ':' in middle and simple_email_re.match(middle):
  219. local, domain = middle.rsplit('@', 1)
  220. try:
  221. domain = domain.encode('idna').decode('ascii')
  222. except UnicodeError:
  223. continue
  224. url = 'mailto:%s@%s' % (local, domain)
  225. nofollow_attr = ''
  226. # Make link.
  227. if url:
  228. trimmed = trim_url(middle)
  229. if autoescape and not safe_input:
  230. lead, trail = escape(lead), escape(trail)
  231. url, trimmed = escape(url), escape(trimmed)
  232. middle = '<a href="%s"%s>%s</a>' % (url, nofollow_attr, trimmed)
  233. words[i] = mark_safe('%s%s%s' % (lead, middle, trail))
  234. else:
  235. if safe_input:
  236. words[i] = mark_safe(word)
  237. elif autoescape:
  238. words[i] = escape(word)
  239. elif safe_input:
  240. words[i] = mark_safe(word)
  241. elif autoescape:
  242. words[i] = escape(word)
  243. return ''.join(words)
  244. urlize = allow_lazy(urlize, six.text_type)
  245. def avoid_wrapping(value):
  246. """
  247. Avoid text wrapping in the middle of a phrase by adding non-breaking
  248. spaces where there previously were normal spaces.
  249. """
  250. return value.replace(" ", "\xa0")