utils.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. from datetime import timedelta
  2. from unidecode import unidecode
  3. from django.http import Http404
  4. from django.core.urlresolvers import resolve, reverse
  5. from django.template.defaultfilters import slugify as django_slugify
  6. from django.utils.translation import ugettext_lazy as _, ungettext_lazy
  7. def slugify(string):
  8. string = unicode(string)
  9. string = unidecode(string)
  10. return django_slugify(string.replace('_', ' ').strip())
  11. """
  12. Return path utility
  13. """
  14. def clean_return_path(request):
  15. if request.method == 'POST' and 'return_path' in request.POST:
  16. return _get_return_path_from_post(request)
  17. else:
  18. return _get_return_path_from_referer(request)
  19. def _get_return_path_from_post(request):
  20. return_path = request.POST.get('return_path')
  21. try:
  22. if not return_path:
  23. raise ValueError()
  24. if not return_path.startswith('/'):
  25. raise ValueError()
  26. resolve(return_path)
  27. return return_path
  28. except (Http404, ValueError):
  29. return None
  30. def _get_return_path_from_referer(request):
  31. referer = request.META.get('HTTP_REFERER')
  32. try:
  33. if not referer:
  34. raise ValueError()
  35. if not referer.startswith(request.scheme):
  36. raise ValueError()
  37. referer = referer[len(request.scheme) + 3:]
  38. if not referer.startswith(request.META['HTTP_HOST']):
  39. raise ValueError()
  40. referer = referer[len(request.META['HTTP_HOST'].rstrip('/')):]
  41. if not referer.startswith('/'):
  42. raise ValueError()
  43. resolve(referer)
  44. return referer
  45. except (Http404, KeyError, ValueError):
  46. return None
  47. """
  48. Utils for resolving requests destination
  49. """
  50. def _is_request_path_under_misago(request):
  51. # We are assuming that forum_index link is root of all Misago links
  52. forum_index = reverse('misago:index')
  53. path_info = request.path_info
  54. if len(forum_index) > len(path_info):
  55. return False
  56. return path_info[:len(forum_index)] == forum_index
  57. def is_request_to_misago(request):
  58. try:
  59. return request._request_to_misago
  60. except AttributeError:
  61. request._request_to_misago = _is_request_path_under_misago(request)
  62. return request._request_to_misago
  63. def is_referer_local(request):
  64. referer = request.META.get('HTTP_REFERER')
  65. if not referer:
  66. return False
  67. if not referer.startswith(request.scheme):
  68. return False
  69. referer = referer[len(request.scheme) + 3:]
  70. if not referer.startswith(request.META['HTTP_HOST']):
  71. return False
  72. referer = referer[len(request.META['HTTP_HOST'].rstrip('/')):]
  73. if not referer.startswith('/'):
  74. return False
  75. return True
  76. """
  77. Utility that humanizes time amount.
  78. Expects number of seconds as first argument
  79. """
  80. def time_amount(value):
  81. delta = timedelta(seconds=value)
  82. units_dict = {
  83. 'd': delta.days,
  84. 'h': 0,
  85. 'm': 0,
  86. 's': delta.seconds,
  87. }
  88. if units_dict['s'] >= 3600:
  89. units_dict['h'] = units_dict['s'] / 3600
  90. units_dict['s'] -= units_dict['h'] * 3600
  91. if units_dict['s'] >= 60:
  92. units_dict['m'] = units_dict['s'] / 60
  93. units_dict['s'] -= units_dict['m'] * 60
  94. precisions = []
  95. if units_dict['d']:
  96. string = ungettext_lazy(
  97. '%(days)s day', '%(days)s days', units_dict['d'])
  98. precisions.append(string % {'days': units_dict['d']})
  99. if units_dict['h']:
  100. string = ungettext_lazy(
  101. '%(hours)s hour', '%(hours)s hours', units_dict['h'])
  102. precisions.append(string % {'hours': units_dict['h']})
  103. if units_dict['m']:
  104. string = ungettext_lazy(
  105. '%(minutes)s minute', '%(minutes)s minutes', units_dict['m'])
  106. precisions.append(string % {'minutes': units_dict['m']})
  107. if units_dict['s']:
  108. string = ungettext_lazy(
  109. '%(seconds)s second', '%(seconds)s seconds', units_dict['s'])
  110. precisions.append(string % {'seconds': units_dict['s']})
  111. if not precisions:
  112. precisions.append(_("0 seconds"))
  113. if len(precisions) == 1:
  114. return precisions[0]
  115. else:
  116. formats = {
  117. 'first_part': ', '.join(precisions[:-1]),
  118. 'and_part': precisions[-1],
  119. }
  120. return _("%(first_part)s and %(and_part)s") % formats
  121. """
  122. MD subset for use for enchancing items descriptions
  123. """
  124. MD_SUBSET_FORBID_SYNTAX = (
  125. # References are evil
  126. 'reference', 'reference', 'image_reference', 'short_reference',
  127. # Blocks are evil too
  128. 'hashheader', 'setextheader', 'code', 'quote', 'hr', 'olist', 'ulist',
  129. )