PageRenderTime 25ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/django/utils/html.py

https://bitbucket.org/loewis/django-3k-old/
Python | 170 lines | 149 code | 7 blank | 14 comment | 5 complexity | 1397fc06a97b0ecf1d32b0553ff6b4db MD5 | raw file
Possible License(s): BSD-3-Clause
  1. """HTML utilities suitable for global use."""
  2. import re
  3. import string
  4. from django.utils.safestring import SafeData, mark_safe
  5. from django.utils.encoding import force_unicode
  6. from django.utils.functional import allow_lazy
  7. from django.utils.http import urlquote
  8. # Configuration for urlize() function.
  9. LEADING_PUNCTUATION = ['(', '<', '&lt;']
  10. TRAILING_PUNCTUATION = ['.', ',', ')', '>', '\n', '&gt;']
  11. # List of possible strings used for bullets in bulleted lists.
  12. DOTS = ['&middot;', '*', '\xe2\x80\xa2', '&#149;', '&bull;', '&#8226;']
  13. unencoded_ampersands_re = re.compile(r'&(?!(\w+|#\d+);)')
  14. word_split_re = re.compile(r'(\s+)')
  15. punctuation_re = re.compile('^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$' % \
  16. ('|'.join([re.escape(x) for x in LEADING_PUNCTUATION]),
  17. '|'.join([re.escape(x) for x in TRAILING_PUNCTUATION])))
  18. simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')
  19. link_target_attribute_re = re.compile(r'(<a [^>]*?)target=[^\s>]+')
  20. html_gunk_re = re.compile(r'(?:<br clear="all">|<i><\/i>|<b><\/b>|<em><\/em>|<strong><\/strong>|<\/?smallcaps>|<\/?uppercase>)', re.IGNORECASE)
  21. hard_coded_bullets_re = re.compile(r'((?:<p>(?:%s).*?[a-zA-Z].*?</p>\s*)+)' % '|'.join([re.escape(x) for x in DOTS]), re.DOTALL)
  22. trailing_empty_content_re = re.compile(r'(?:<p>(?:&nbsp;|\s|<br \/>)*?</p>\s*)+\Z')
  23. try:
  24. del x # Temporary variable, gone in 3k
  25. except NameError:
  26. pass
  27. def escape(html):
  28. """
  29. Returns the given HTML with ampersands, quotes and angle brackets encoded.
  30. """
  31. return mark_safe(force_unicode(html).replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;'))
  32. escape = allow_lazy(escape, unicode)
  33. def conditional_escape(html):
  34. """
  35. Similar to escape(), except that it doesn't operate on pre-escaped strings.
  36. """
  37. if isinstance(html, SafeData):
  38. return html
  39. else:
  40. return escape(html)
  41. def linebreaks(value, autoescape=False):
  42. """Converts newlines into <p> and <br />s."""
  43. value = re.sub(r'\r\n|\r|\n', '\n', force_unicode(value)) # normalize newlines
  44. paras = re.split('\n{2,}', value)
  45. if autoescape:
  46. paras = [u'<p>%s</p>' % escape(p).replace('\n', '<br />') for p in paras]
  47. else:
  48. paras = [u'<p>%s</p>' % p.replace('\n', '<br />') for p in paras]
  49. return u'\n\n'.join(paras)
  50. linebreaks = allow_lazy(linebreaks, unicode)
  51. def strip_tags(value):
  52. """Returns the given HTML with all tags stripped."""
  53. return re.sub(r'<[^>]*?>', '', force_unicode(value))
  54. strip_tags = allow_lazy(strip_tags)
  55. def strip_spaces_between_tags(value):
  56. """Returns the given HTML with spaces between tags removed."""
  57. return re.sub(r'>\s+<', '><', force_unicode(value))
  58. strip_spaces_between_tags = allow_lazy(strip_spaces_between_tags, unicode)
  59. def strip_entities(value):
  60. """Returns the given HTML with all entities (&something;) stripped."""
  61. return re.sub(r'&(?:\w+|#\d+);', '', force_unicode(value))
  62. strip_entities = allow_lazy(strip_entities, unicode)
  63. def fix_ampersands(value):
  64. """Returns the given HTML with all unencoded ampersands encoded correctly."""
  65. return unencoded_ampersands_re.sub('&amp;', force_unicode(value))
  66. fix_ampersands = allow_lazy(fix_ampersands, unicode)
  67. def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
  68. """
  69. Converts any URLs in text into clickable links.
  70. Works on http://, https://, www. links and links ending in .org, .net or
  71. .com. Links can have trailing punctuation (periods, commas, close-parens)
  72. and leading punctuation (opening parens) and it'll still do the right
  73. thing.
  74. If trim_url_limit is not None, the URLs in link text longer than this limit
  75. will truncated to trim_url_limit-3 characters and appended with an elipsis.
  76. If nofollow is True, the URLs in link text will get a rel="nofollow"
  77. attribute.
  78. If autoescape is True, the link text and URLs will get autoescaped.
  79. """
  80. 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
  81. safe_input = isinstance(text, SafeData)
  82. words = word_split_re.split(force_unicode(text))
  83. nofollow_attr = nofollow and ' rel="nofollow"' or ''
  84. for i, word in enumerate(words):
  85. match = None
  86. if '.' in word or '@' in word or ':' in word:
  87. match = punctuation_re.match(word)
  88. if match:
  89. lead, middle, trail = match.groups()
  90. # Make URL we want to point to.
  91. url = None
  92. if middle.startswith('http://') or middle.startswith('https://'):
  93. url = urlquote(middle, safe='/&=:;#?+*')
  94. elif middle.startswith('www.') or ('@' not in middle and \
  95. middle and middle[0] in string.ascii_letters + string.digits and \
  96. (middle.endswith('.org') or middle.endswith('.net') or middle.endswith('.com'))):
  97. url = urlquote('http://%s' % middle, safe='/&=:;#?+*')
  98. elif '@' in middle and not ':' in middle and simple_email_re.match(middle):
  99. url = 'mailto:%s' % middle
  100. nofollow_attr = ''
  101. # Make link.
  102. if url:
  103. trimmed = trim_url(middle)
  104. if autoescape and not safe_input:
  105. lead, trail = escape(lead), escape(trail)
  106. url, trimmed = escape(url), escape(trimmed)
  107. middle = '<a href="%s"%s>%s</a>' % (url, nofollow_attr, trimmed)
  108. words[i] = mark_safe('%s%s%s' % (lead, middle, trail))
  109. else:
  110. if safe_input:
  111. words[i] = mark_safe(word)
  112. elif autoescape:
  113. words[i] = escape(word)
  114. elif safe_input:
  115. words[i] = mark_safe(word)
  116. elif autoescape:
  117. words[i] = escape(word)
  118. return u''.join(words)
  119. urlize = allow_lazy(urlize, unicode)
  120. def clean_html(text):
  121. """
  122. Clean the given HTML. Specifically, do the following:
  123. * Convert <b> and <i> to <strong> and <em>.
  124. * Encode all ampersands correctly.
  125. * Remove all "target" attributes from <a> tags.
  126. * Remove extraneous HTML, such as presentational tags that open and
  127. immediately close and <br clear="all">.
  128. * Convert hard-coded bullets into HTML unordered lists.
  129. * Remove stuff like "<p>&nbsp;&nbsp;</p>", but only if it's at the
  130. bottom of the text.
  131. """
  132. from django.utils.text import normalize_newlines
  133. text = normalize_newlines(force_unicode(text))
  134. text = re.sub(r'<(/?)\s*b\s*>', '<\\1strong>', text)
  135. text = re.sub(r'<(/?)\s*i\s*>', '<\\1em>', text)
  136. text = fix_ampersands(text)
  137. # Remove all target="" attributes from <a> tags.
  138. text = link_target_attribute_re.sub('\\1', text)
  139. # Trim stupid HTML such as <br clear="all">.
  140. text = html_gunk_re.sub('', text)
  141. # Convert hard-coded bullets into HTML unordered lists.
  142. def replace_p_tags(match):
  143. s = match.group().replace('</p>', '</li>')
  144. for d in DOTS:
  145. s = s.replace('<p>%s' % d, '<li>')
  146. return u'<ul>\n%s\n</ul>' % s
  147. text = hard_coded_bullets_re.sub(replace_p_tags, text)
  148. # Remove stuff like "<p>&nbsp;&nbsp;</p>", but only if it's at the bottom
  149. # of the text.
  150. text = trailing_empty_content_re.sub('', text)
  151. return text
  152. clean_html = allow_lazy(clean_html, unicode)