factory.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 signature_markdown(acl, text):
  8. md = markdown.Markdown(
  9. safe_mode='escape',
  10. output_format=settings.OUTPUT_FORMAT,
  11. extensions=['nl2br'])
  12. if not acl.usercp.allow_signature_links():
  13. del md.inlinePatterns['link']
  14. del md.inlinePatterns['autolink']
  15. if not acl.usercp.allow_signature_images():
  16. del md.inlinePatterns['image_link']
  17. del md.inlinePatterns['image_reference']
  18. del md.parser.blockprocessors['hashheader']
  19. del md.parser.blockprocessors['setextheader']
  20. del md.parser.blockprocessors['code']
  21. del md.parser.blockprocessors['quote']
  22. del md.parser.blockprocessors['hr']
  23. del md.parser.blockprocessors['olist']
  24. del md.parser.blockprocessors['ulist']
  25. return md.convert(text)
  26. def post_markdown(request, text):
  27. md = markdown.Markdown(
  28. safe_mode='escape',
  29. output_format=settings.OUTPUT_FORMAT,
  30. extensions=['nl2br', 'fenced_code'])
  31. md.mi_token = get_random_string(16)
  32. for extension in settings.MARKDOWN_EXTENSIONS:
  33. module = '.'.join(extension.split('.')[:-1])
  34. extension = extension.split('.')[-1]
  35. module = import_module(module)
  36. attr = getattr(module, extension)
  37. ext = attr()
  38. ext.extendMarkdown(md)
  39. text = md.convert(text)
  40. # Final cleanups
  41. text = text.replace('<p><h3><quotetitle>', '<h3><quotetitle>')
  42. text = text.replace('</quotetitle></h3></p>', '</quotetitle></h3>')
  43. text = text.replace('</quotetitle></h3><br>\n', '</quotetitle></h3>\n<p>')
  44. text = text.replace('\n<p></p>', '')
  45. def trans_quotetitle(match):
  46. return _("Posted by %(user)s") % {'user': match.group('content')}
  47. text = re.sub(r'<quotetitle>(?P<content>.+)</quotetitle>', trans_quotetitle, text)
  48. return text