PageRenderTime 157ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 0ms

/src/lbforum/templatetags/helper.py

https://github.com/macdylan/LBForum
Python | 44 lines | 38 code | 4 blank | 2 comment | 6 complexity | fd990c975a4b124f16959342571d5ab4 MD5 | raw file
  1. #!/usr/bin/env python
  2. # -*- coding: UTF-8 -*-
  3. from BeautifulSoup import BeautifulSoup, NavigableString
  4. from django.conf import settings
  5. acceptable_elements = ['a', 'abbr', 'acronym', 'address', 'area', 'b', 'big',
  6. 'blockquote', 'br', 'button', 'caption', 'center', 'cite', 'code', 'col',
  7. 'colgroup', 'dd', 'del', 'dfn', 'dir', 'div', 'dl', 'dt', 'em',
  8. 'font', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img',
  9. 'ins', 'kbd', 'label', 'legend', 'li', 'map', 'menu', 'ol',
  10. 'p', 'pre', 'q', 's', 'samp', 'small', 'span', 'strike',
  11. 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th',
  12. 'thead', 'tr', 'tt', 'u', 'ul', 'var']
  13. acceptable_attributes = ['abbr', 'accept', 'accept-charset', 'accesskey',
  14. 'action', 'align', 'alt', 'axis', 'border', 'cellpadding', 'cellspacing',
  15. 'char', 'charoff', 'charset', 'checked', 'cite', 'clear', 'cols',
  16. 'colspan', 'color', 'compact', 'coords', 'datetime', 'dir',
  17. 'enctype', 'for', 'headers', 'height', 'href', 'hreflang', 'hspace',
  18. 'id', 'ismap', 'label', 'lang', 'longdesc', 'maxlength', 'method',
  19. 'multiple', 'name', 'nohref', 'noshade', 'nowrap', 'prompt',
  20. 'rel', 'rev', 'rows', 'rowspan', 'rules', 'scope', 'shape', 'size',
  21. 'span', 'src', 'start', 'summary', 'tabindex', 'target', 'title', 'type',
  22. 'usemap', 'valign', 'value', 'vspace', 'width', 'style']
  23. acceptable_elements.extend(getattr(settings, 'HTML_SAFE_TAGS', []))
  24. acceptable_attributes.extend(getattr(settings, 'HTML_SAFE_ATTRS', []))
  25. acceptable_elements = set(acceptable_elements) - set(getattr(settings, 'HTML_UNSAFE_TAGS', []))
  26. acceptable_attributes = set(acceptable_attributes) - set(getattr(settings, 'HTML_UNSAFE_ATTRS', []))
  27. def clean_html( fragment ):
  28. soup = BeautifulSoup( fragment.strip() )
  29. def cleanup( soup ):
  30. for tag in soup:
  31. if not isinstance( tag, NavigableString):
  32. if tag.name not in acceptable_elements:
  33. tag.extract()
  34. else:
  35. for attr in tag._getAttrMap().keys():
  36. if attr not in acceptable_attributes:
  37. del tag[attr]
  38. cleanup( tag )
  39. cleanup( soup )
  40. return unicode( soup )