]> git.openstreetmap.org Git - osqa.git/blob - forum/templatetags/extra_tags.py
e01ff068d3377863add7c536c833ff156dee2516
[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     # We get the number of all user's answers.
90     total_answers_count = Answer.objects.filter(author=user).count()
91
92     # We get the number of the user's accepted answers.
93     accepted_answers_count = Answer.objects.filter(author=user, state_string__contains="(accepted)").count()
94
95     # In order to represent the accept rate in percentages we divide the number of the accepted answers to the
96     # total answers count and make a hundred multiplication.
97     try:
98         accept_rate = (float(accepted_answers_count) / float(total_answers_count) * 100)
99     except ZeroDivisionError:
100         accept_rate = 0
101
102     # If the user has more than one accepted answers the rate title will be in plural.
103     if accepted_answers_count > 1:
104         accept_rate_number_title = _('%(user)s has %(count)d accepted answers') % {
105             'user' :  smart_unicode(user.username),
106             'count' : int(accepted_answers_count)
107         }
108     # If the user has one accepted answer we'll be using singular.
109     elif accepted_answers_count == 1:
110         accept_rate_number_title = _('%s has one accepted answer') % smart_unicode(user.username)
111     # This are the only options. Otherwise there are no accepted answers at all.
112     else:
113         accept_rate_number_title = _('%s has no accepted answers') % smart_unicode(user.username)
114
115     html_output = """
116     <span title="%(accept_rate_title)s" class="accept_rate">%(accept_rate_label)s:</span>
117     <span title="%(accept_rate_number_title)s">%(accept_rate)d&#37;</span>
118     """ % {
119         'accept_rate_label' : _('accept rate'),
120         'accept_rate_title' : _('Rate of the user\'s accepted answers'),
121         'accept_rate' : int(accept_rate),
122         'accept_rate_number_title' : u'%s' % accept_rate_number_title,
123     }
124
125     return mark_safe(html_output)
126
127 @register.simple_tag
128 def get_age(birthday):
129     current_time = datetime.datetime(*time.localtime()[0:6])
130     year = birthday.year
131     month = birthday.month
132     day = birthday.day
133     diff = current_time - datetime.datetime(year, month, day, 0, 0, 0)
134     return diff.days / 365
135
136 @register.simple_tag
137 def diff_date(date, limen=2):
138     if not date:
139         return _('unknown')
140
141     now = datetime.datetime.now()
142     diff = now - date
143     days = diff.days
144     hours = int(diff.seconds/3600)
145     minutes = int(diff.seconds/60)
146
147     if date.year != now.year:
148         return dateformat.format(date, 'd M \'y, H:i')
149     elif days > 2:
150         return dateformat.format(date, 'd M, H:i')
151
152     elif days == 2:
153         return _('2 days ago')
154     elif days == 1:
155         return _('yesterday')
156     elif minutes >= 60:
157         return ungettext('%(hr)d ' + _("hour ago"), '%(hr)d ' + _("hours ago"), hours) % {'hr':hours}
158     elif diff.seconds >= 60:
159         return ungettext('%(min)d ' + _("min ago"), '%(min)d ' + _("mins ago"), minutes) % {'min':minutes}
160     else:
161         return ungettext('%(sec)d ' + _("sec ago"), '%(sec)d ' + _("secs ago"), diff.seconds) % {'sec':diff.seconds}
162
163 @register.simple_tag
164 def media(url):
165     url = skins.find_media_source(url)
166     if url:
167         # Create the URL prefix.
168         url_prefix = settings.FORCE_SCRIPT_NAME + '/m/'
169
170         # Make sure any duplicate forward slashes are replaced with a single
171         # forward slash.
172         url_prefix = re.sub("/+", "/", url_prefix)
173
174         url = url_prefix + url
175         return url
176
177 @register.simple_tag
178 def get_tag_font_size(tag):
179     occurrences_of_current_tag = tag.used_count
180
181     # Occurrences count settings
182     min_occurs = int(settings.TAGS_CLOUD_MIN_OCCURS)
183     max_occurs = int(settings.TAGS_CLOUD_MAX_OCCURS)
184
185     # Font size settings
186     min_font_size = int(settings.TAGS_CLOUD_MIN_FONT_SIZE)
187     max_font_size = int(settings.TAGS_CLOUD_MAX_FONT_SIZE)
188
189     # Calculate the font size of the tag according to the occurrences count
190     weight = (math.log(occurrences_of_current_tag)-math.log(min_occurs))/(math.log(max_occurs)-math.log(min_occurs))
191     font_size_of_current_tag = min_font_size + int(math.floor((max_font_size-min_font_size)*weight))
192
193     return font_size_of_current_tag
194
195 class ItemSeparatorNode(template.Node):
196     def __init__(self, separator):
197         sep = separator.strip()
198         if sep[0] == sep[-1] and sep[0] in ('\'', '"'):
199             sep = sep[1:-1]
200         else:
201             raise template.TemplateSyntaxError('separator in joinitems tag must be quoted')
202         self.content = sep
203
204     def render(self, context):
205         return self.content
206
207 class BlockMediaUrlNode(template.Node):
208     def __init__(self, nodelist):
209         self.items = nodelist
210
211     def render(self, context):
212         prefix = settings.APP_URL + 'm/'
213         url = ''
214         if self.items:
215             url += '/'
216         for item in self.items:
217             url += item.render(context)
218
219         url = skins.find_media_source(url)
220         url = prefix + url
221         out = url
222         return out.replace(' ', '')
223
224 @register.tag(name='blockmedia')
225 def blockmedia(parser, token):
226     try:
227         tagname = token.split_contents()
228     except ValueError:
229         raise template.TemplateSyntaxError("blockmedia tag does not use arguments")
230     nodelist = []
231     while True:
232         nodelist.append(parser.parse(('endblockmedia')))
233         next = parser.next_token()
234         if next.contents == 'endblockmedia':
235             break
236     return BlockMediaUrlNode(nodelist)
237
238
239 @register.simple_tag
240 def fullmedia(url):
241     domain = settings.APP_BASE_URL
242     #protocol = getattr(settings, "PROTOCOL", "http")
243     path = media(url)
244     return "%s%s" % (domain, path)
245
246
247 class SimpleVarNode(template.Node):
248     def __init__(self, name, value):
249         self.name = name
250         self.value = template.Variable(value)
251
252     def render(self, context):
253         context[self.name] = self.value.resolve(context)
254         return ''
255
256 class BlockVarNode(template.Node):
257     def __init__(self, name, block):
258         self.name = name
259         self.block = block
260
261     def render(self, context):
262         source = self.block.render(context)
263         context[self.name] = source.strip()
264         return ''
265
266
267 @register.tag(name='var')
268 def do_var(parser, token):
269     tokens = token.split_contents()[1:]
270
271     if not len(tokens) or not re.match('^\w+$', tokens[0]):
272         raise template.TemplateSyntaxError("Expected variable name")
273
274     if len(tokens) == 1:
275         nodelist = parser.parse(('endvar',))
276         parser.delete_first_token()
277         return BlockVarNode(tokens[0], nodelist)
278     elif len(tokens) == 3:
279         return SimpleVarNode(tokens[0], tokens[2])
280
281     raise template.TemplateSyntaxError("Invalid number of arguments")
282
283 class DeclareNode(template.Node):
284     dec_re = re.compile('^\s*(\w+)\s*(:?=)\s*(.*)$')
285
286     def __init__(self, block):
287         self.block = block
288
289     def render(self, context):
290         source = self.block.render(context)
291
292         for line in source.splitlines():
293             m = self.dec_re.search(line)
294             if m:
295                 clist = list(context)
296                 clist.reverse()
297                 d = {}
298                 d['_'] = _
299                 d['os'] = os
300                 d['html'] = html
301                 d['reverse'] = reverse
302                 d['settings'] = settings
303                 d['smart_str'] = smart_str
304                 d['smart_unicode'] = smart_unicode
305                 d['force_unicode'] = force_unicode
306                 for c in clist:
307                     d.update(c)
308                 try:
309                     command = m.group(3).strip()
310                     context[m.group(1).strip()] = eval(command, d)
311                 except Exception, e:
312                     logging.error("Error in declare tag, when evaluating: %s" % m.group(3).strip())
313         return ''
314
315 @register.tag(name='declare')
316 def do_declare(parser, token):
317     nodelist = parser.parse(('enddeclare',))
318     parser.delete_first_token()
319     return DeclareNode(nodelist)
320
321 # Usage: {% random 1 999 %}
322 # Generates random number in the template
323 class RandomNumberNode(template.Node):
324     # We get the limiting numbers
325     def __init__(self, int_from, int_to):
326         self.int_from = int(int_from)
327         self.int_to = int(int_to)
328
329     # We generate the random number using the standard python interface
330     def render(self, context):
331         return str(random.randint(self.int_from, self.int_to))
332
333 @register.tag(name="random")
334 def random_number(parser, token):
335     # Try to get the limiting numbers from the token
336     try:
337         tag_name, int_from, int_to = token.split_contents()
338     except ValueError:
339         # If we had no success -- raise an exception
340         raise template.TemplateSyntaxError, "%r tag requires exactly two arguments" % token.contents.split()[0]
341
342     # Call the random Node
343     return RandomNumberNode(int_from, int_to)