factory.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import re
  2. import markdown
  3. from django.conf import settings
  4. from django.utils.importlib import import_module
  5. from django.utils.translation import ugettext_lazy as _
  6. from misago.utils import get_random_string
  7. def remove_unsupported(md):
  8. # References are evil, we dont support them
  9. del md.preprocessors['reference']
  10. del md.inlinePatterns['reference']
  11. del md.inlinePatterns['image_reference']
  12. del md.inlinePatterns['short_reference']
  13. def signature_markdown(acl, text):
  14. md = markdown.Markdown(
  15. safe_mode='escape',
  16. output_format=settings.OUTPUT_FORMAT,
  17. extensions=['nl2br'])
  18. remove_unsupported(md)
  19. if not acl.usercp.allow_signature_links():
  20. del md.inlinePatterns['link']
  21. del md.inlinePatterns['autolink']
  22. if not acl.usercp.allow_signature_images():
  23. del md.inlinePatterns['image_link']
  24. del md.parser.blockprocessors['hashheader']
  25. del md.parser.blockprocessors['setextheader']
  26. del md.parser.blockprocessors['code']
  27. del md.parser.blockprocessors['quote']
  28. del md.parser.blockprocessors['hr']
  29. del md.parser.blockprocessors['olist']
  30. del md.parser.blockprocessors['ulist']
  31. return md.convert(text)
  32. def post_markdown(request, text):
  33. md = markdown.Markdown(
  34. safe_mode='escape',
  35. output_format=settings.OUTPUT_FORMAT,
  36. extensions=['nl2br', 'fenced_code'])
  37. remove_unsupported(md)
  38. md.mi_token = get_random_string(16)
  39. for extension in settings.MARKDOWN_EXTENSIONS:
  40. module = '.'.join(extension.split('.')[:-1])
  41. extension = extension.split('.')[-1]
  42. module = import_module(module)
  43. attr = getattr(module, extension)
  44. ext = attr()
  45. ext.extendMarkdown(md)
  46. text = md.convert(text)
  47. # Final cleanups
  48. text = text.replace('<p><h3><quotetitle>', '<h3><quotetitle>')
  49. text = text.replace('</quotetitle></h3></p>', '</quotetitle></h3>')
  50. text = text.replace('</quotetitle></h3><br>\n', '</quotetitle></h3>\n<p>')
  51. text = text.replace('\n<p></p>', '')
  52. def trans_quotetitle(match):
  53. return _("Posted by %(user)s") % {'user': match.group('content')}
  54. text = re.sub(r'<quotetitle>(?P<content>.+)</quotetitle>', trans_quotetitle, text)
  55. return text