]> git.openstreetmap.org Git - osqa.git/blob - forum/templatetags/extra_tags.py
b8d9f5cad3ce18c49189200856c6b2f5d764c7e7
[osqa.git] / forum / templatetags / extra_tags.py
1 import time
2 import os
3 import posixpath
4 import datetime
5 import math
6 import re
7 import logging
8 import random
9 from django import template
10 from django.utils.encoding import smart_unicode, force_unicode, smart_str
11 from django.utils.safestring import mark_safe
12 from django.utils import dateformat
13 from forum.models import Question, Answer, QuestionRevision, AnswerRevision, NodeRevision
14 from django.utils.translation import ugettext as _
15 from django.utils.translation import ungettext
16 from django.utils import simplejson
17 from forum import settings
18 from django.template.defaulttags import url as default_url
19 from forum import skins
20 from forum.utils import html
21 from extra_filters import decorated_int
22 from django.core.urlresolvers import reverse
23
24 register = template.Library()
25
26 GRAVATAR_TEMPLATE = ('<img class="gravatar" width="%(size)s" height="%(size)s" '
27 'src="https://secure.gravatar.com/avatar/%(gravatar_hash)s'
28 '?s=%(size)s&amp;d=%(default)s&amp;r=%(rating)s" '
29 'alt="%(username)s\'s gravatar image" />')
30
31 @register.simple_tag
32 def gravatar(user, size):
33     try:
34         gravatar = user['gravatar']
35         username = user['username']
36     except (TypeError, AttributeError, KeyError):
37         gravatar = user.gravatar
38         username = user.username
39     return mark_safe(GRAVATAR_TEMPLATE % {
40     'size': size,
41     'gravatar_hash': gravatar,
42     'default': settings.GRAVATAR_DEFAULT_IMAGE,
43     'rating': settings.GRAVATAR_ALLOWED_RATING,
44     'username': template.defaultfilters.urlencode(username),
45     })
46
47
48 @register.simple_tag
49 def get_score_badge(user):
50     if user.is_suspended():
51         return _("(suspended)")
52
53     repstr = decorated_int(user.reputation, "")
54
55     BADGE_TEMPLATE = '<span class="score" title="%(reputation)s %(reputationword)s">%(repstr)s</span>'
56     if user.gold > 0 :
57         BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, '<span title="%(gold)s %(badgesword)s">'
58         '<span class="badge1">&#9679;</span>'
59         '<span class="badgecount">%(gold)s</span>'
60         '</span>')
61     if user.silver > 0:
62         BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, '<span title="%(silver)s %(badgesword)s">'
63         '<span class="silver">&#9679;</span>'
64         '<span class="badgecount">%(silver)s</span>'
65         '</span>')
66     if user.bronze > 0:
67         BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, '<span title="%(bronze)s %(badgesword)s">'
68         '<span class="bronze">&#9679;</span>'
69         '<span class="badgecount">%(bronze)s</span>'
70         '</span>')
71     BADGE_TEMPLATE = smart_unicode(BADGE_TEMPLATE, encoding='utf-8', strings_only=False, errors='strict')
72     return mark_safe(BADGE_TEMPLATE % {
73     'reputation' : user.reputation,
74     'repstr': repstr,
75     'gold' : user.gold,
76     'silver' : user.silver,
77     'bronze' : user.bronze,
78     'badgesword' : _('badges'),
79     'reputationword' : _('reputation points'),
80     })
81
82 # Usage: {% get_accept_rate node.author %}
83 @register.simple_tag
84 def get_accept_rate(user):
85     # If the Show Accept Rate feature is not activated this tag should return a blank string
86     if not settings.SHOW_USER_ACCEPT_RATE:
87         return ""
88
89     # Freeze accept rate for users
90     freeze_accept_rate_for_users_users = settings.FREEZE_ACCEPT_RATE_FOR.value
91     if user.username in list(freeze_accept_rate_for_users_users):
92         freeze = True
93     else:
94         freeze = False
95
96     # We get the number of all user's answers.
97     total_answers_count = Answer.objects.filter(author=user).count()
98
99     # We get the number of the user's accepted answers.
100     accepted_answers_count = Answer.objects.filter(author=user, state_string__contains="(accepted)").count()
101
102     # In order to represent the accept rate in percentages we divide the number of the accepted answers to the
103     # total answers count and make a hundred multiplication.
104     try:
105         accept_rate = (float(accepted_answers_count) / float(total_answers_count) * 100)
106     except ZeroDivisionError:
107         accept_rate = 0
108
109     # If the user has more than one accepted answers the rate title will be in plural.
110     if accepted_answers_count > 1:
111         accept_rate_number_title = _('%(user)s has %(count)d accepted answers') % {
112             'user' :  smart_unicode(user.username),
113             'count' : int(accepted_answers_count)
114         }
115     # If the user has one accepted answer we'll be using singular.
116     elif accepted_answers_count == 1:
117         accept_rate_number_title = _('%s has one accepted answer') % smart_unicode(user.username)
118     # This are the only options. Otherwise there are no accepted answers at all.
119     else:
120         if freeze:
121             accept_rate_number_title = ""
122         else:
123             accept_rate_number_title = _('%s has no accepted answers') % smart_unicode(user.username)
124
125     html_output = """
126     <span title="%(accept_rate_title)s" class="accept_rate">%(accept_rate_label)s:</span>
127     <span title="%(accept_rate_number_title)s">%(accept_rate)d&#37;</span>
128     """ % {
129         'accept_rate_label' : _('accept rate'),
130         'accept_rate_title' : _('Rate of the user\'s accepted answers'),
131         'accept_rate' : 100 if freeze else int(accept_rate),
132         'accept_rate_number_title' : u'%s' % accept_rate_number_title,
133     }
134
135     return mark_safe(html_output)
136
137 @register.simple_tag
138 def get_age(birthday):
139     current_time = datetime.datetime(*time.localtime()[0:6])
140     year = birthday.year
141     month = birthday.month
142     day = birthday.day
143     diff = current_time - datetime.datetime(year, month, day, 0, 0, 0)
144     return diff.days / 365
145
146 @register.simple_tag
147 def diff_date(date, limen=2):
148     if not date:
149         return _('unknown')
150
151     now = datetime.datetime.now()
152     diff = now - date
153     days = diff.days
154     hours = int(diff.seconds/3600)
155     minutes = int(diff.seconds/60)
156
157     if date.year != now.year:
158         return dateformat.format(date, 'd M \'y, H:i')
159     elif days > 2:
160         return dateformat.format(date, 'd M, H:i')
161
162     elif days == 2:
163         return _('2 days ago')
164     elif days == 1:
165         return _('yesterday')
166     elif minutes >= 60:
167         return ungettext('%(hr)d ' + _("hour ago"), '%(hr)d ' + _("hours ago"), hours) % {'hr':hours}
168     elif diff.seconds >= 60:
169         return ungettext('%(min)d ' + _("min ago"), '%(min)d ' + _("mins ago"), minutes) % {'min':minutes}
170     else:
171         return ungettext('%(sec)d ' + _("sec ago"), '%(sec)d ' + _("secs ago"), diff.seconds) % {'sec':diff.seconds}
172
173 @register.simple_tag
174 def media(url):
175     url = skins.find_media_source(url)
176     if url:
177         # Create the URL prefix.
178         url_prefix = settings.FORCE_SCRIPT_NAME + '/m/'
179
180         # Make sure any duplicate forward slashes are replaced with a single
181         # forward slash.
182         url_prefix = re.sub("/+", "/", url_prefix)
183
184         url = url_prefix + url
185         return url
186
187 @register.simple_tag
188 def get_tag_font_size(tag):
189     occurrences_of_current_tag = tag.used_count
190
191     # Occurrences count settings
192     min_occurs = int(settings.TAGS_CLOUD_MIN_OCCURS)
193     max_occurs = int(settings.TAGS_CLOUD_MAX_OCCURS)
194
195     # Font size settings
196     min_font_size = int(settings.TAGS_CLOUD_MIN_FONT_SIZE)
197     max_font_size = int(settings.TAGS_CLOUD_MAX_FONT_SIZE)
198
199     # Calculate the font size of the tag according to the occurrences count
200     weight = (math.log(occurrences_of_current_tag)-math.log(min_occurs))/(math.log(max_occurs)-math.log(min_occurs))
201     font_size_of_current_tag = min_font_size + int(math.floor((max_font_size-min_font_size)*weight))
202
203     return font_size_of_current_tag
204
205 class ItemSeparatorNode(template.Node):
206     def __init__(self, separator):
207         sep = separator.strip()
208         if sep[0] == sep[-1] and sep[0] in ('\'', '"'):
209             sep = sep[1:-1]
210         else:
211             raise template.TemplateSyntaxError('separator in joinitems tag must be quoted')
212         self.content = sep
213
214     def render(self, context):
215         return self.content
216
217 class BlockMediaUrlNode(template.Node):
218     def __init__(self, nodelist):
219         self.items = nodelist
220
221     def render(self, context):
222         prefix = settings.APP_URL + 'm/'
223         url = ''
224         if self.items:
225             url += '/'
226         for item in self.items:
227             url += item.render(context)
228
229         url = skins.find_media_source(url)
230         url = prefix + url
231         out = url
232         return out.replace(' ', '')
233
234 @register.tag(name='blockmedia')
235 def blockmedia(parser, token):
236     try:
237         tagname = token.split_contents()
238     except ValueError:
239         raise template.TemplateSyntaxError("blockmedia tag does not use arguments")
240     nodelist = []
241     while True:
242         nodelist.append(parser.parse(('endblockmedia')))
243         next = parser.next_token()
244         if next.contents == 'endblockmedia':
245             break
246     return BlockMediaUrlNode(nodelist)
247
248
249 @register.simple_tag
250 def fullmedia(url):
251     domain = settings.APP_BASE_URL
252     #protocol = getattr(settings, "PROTOCOL", "http")
253     path = media(url)
254     return "%s%s" % (domain, path)
255
256
257 class SimpleVarNode(template.Node):
258     def __init__(self, name, value):
259         self.name = name
260         self.value = template.Variable(value)
261
262     def render(self, context):
263         context[self.name] = self.value.resolve(context)
264         return ''
265
266 class BlockVarNode(template.Node):
267     def __init__(self, name, block):
268         self.name = name
269         self.block = block
270
271     def render(self, context):
272         source = self.block.render(context)
273         context[self.name] = source.strip()
274         return ''
275
276
277 @register.tag(name='var')
278 def do_var(parser, token):
279     tokens = token.split_contents()[1:]
280
281     if not len(tokens) or not re.match('^\w+$', tokens[0]):
282         raise template.TemplateSyntaxError("Expected variable name")
283
284     if len(tokens) == 1:
285         nodelist = parser.parse(('endvar',))
286         parser.delete_first_token()
287         return BlockVarNode(tokens[0], nodelist)
288     elif len(tokens) == 3:
289         return SimpleVarNode(tokens[0], tokens[2])
290
291     raise template.TemplateSyntaxError("Invalid number of arguments")
292
293 class DeclareNode(template.Node):
294     dec_re = re.compile('^\s*(\w+)\s*(:?=)\s*(.*)$')
295
296     def __init__(self, block):
297         self.block = block
298
299     def render(self, context):
300         source = self.block.render(context)
301
302         for line in source.splitlines():
303             m = self.dec_re.search(line)
304             if m:
305                 clist = list(context)
306                 clist.reverse()
307                 d = {}
308                 d['_'] = _
309                 d['os'] = os
310                 d['html'] = html
311                 d['reverse'] = reverse
312                 d['settings'] = settings
313                 d['smart_str'] = smart_str
314                 d['smart_unicode'] = smart_unicode
315                 d['force_unicode'] = force_unicode
316                 for c in clist:
317                     d.update(c)
318                 try:
319                     command = m.group(3).strip()
320                     context[m.group(1).strip()] = eval(command, d)
321                 except Exception, e:
322                     logging.error("Error in declare tag, when evaluating: %s" % m.group(3).strip())
323         return ''
324
325 @register.tag(name='declare')
326 def do_declare(parser, token):
327     nodelist = parser.parse(('enddeclare',))
328     parser.delete_first_token()
329     return DeclareNode(nodelist)
330
331 # Usage: {% random 1 999 %}
332 # Generates random number in the template
333 class RandomNumberNode(template.Node):
334     # We get the limiting numbers
335     def __init__(self, int_from, int_to):
336         self.int_from = int(int_from)
337         self.int_to = int(int_to)
338
339     # We generate the random number using the standard python interface
340     def render(self, context):
341         return str(random.randint(self.int_from, self.int_to))
342
343 @register.tag(name="random")
344 def random_number(parser, token):
345     # Try to get the limiting numbers from the token
346     try:
347         tag_name, int_from, int_to = token.split_contents()
348     except ValueError:
349         # If we had no success -- raise an exception
350         raise template.TemplateSyntaxError, "%r tag requires exactly two arguments" % token.contents.split()[0]
351
352     # Call the random Node
353     return RandomNumberNode(int_from, int_to)