utils.py 4.6 KB

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