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
24 register = template.Library()
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&d=%(default)s&r=%(rating)s" '
29 'alt="%(username)s\'s gravatar image" />')
32 def gravatar(user, size):
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 % {
41 'gravatar_hash': gravatar,
42 'default': settings.GRAVATAR_DEFAULT_IMAGE,
43 'rating': settings.GRAVATAR_ALLOWED_RATING,
44 'username': template.defaultfilters.urlencode(username),
49 def get_score_badge(user):
50 if user.is_suspended():
51 return _("(suspended)")
53 repstr = decorated_int(user.reputation, "")
55 BADGE_TEMPLATE = '<span class="score" title="%(reputation)s %(reputationword)s">%(repstr)s</span>'
57 BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, '<span title="%(gold)s %(badgesword)s">'
58 '<span class="badge1">●</span>'
59 '<span class="badgecount">%(gold)s</span>'
62 BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, '<span title="%(silver)s %(badgesword)s">'
63 '<span class="silver">●</span>'
64 '<span class="badgecount">%(silver)s</span>'
67 BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, '<span title="%(bronze)s %(badgesword)s">'
68 '<span class="bronze">●</span>'
69 '<span class="badgecount">%(bronze)s</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,
76 'silver' : user.silver,
77 'bronze' : user.bronze,
78 'badgesword' : _('badges'),
79 'reputationword' : _('reputation points'),
82 # Usage: {% get_accept_rate node.author %}
84 def get_accept_rate(user):
85 # We get the number of all user's answers.
86 total_answers_count = Answer.objects.filter(author=user).count()
88 # We get the number of the user's accepted answers.
89 accepted_answers_count = Answer.objects.filter(author=user, state_string__contains="(accepted)").count()
91 # In order to represent the accept rate in percentages we divide the number of the accepted answers to the
92 # total answers count and make a hundred multiplication.
94 accept_rate = (float(accepted_answers_count) / float(total_answers_count) * 100)
95 except ZeroDivisionError:
98 # If the user has more than one accepted answers the rate title will be in plural.
99 if accepted_answers_count > 1:
100 accept_rate_number_title = _('%(user)s has %(count)d accepted answers') % {
101 'user' : smart_unicode(user.username),
102 'count' : int(accepted_answers_count)
104 # If the user has one accepted answer we'll be using singular.
105 elif accepted_answers_count == 1:
106 accept_rate_number_title = _('%s has one accepted answer') % user.username
107 # This are the only options. Otherwise there are no accepted answers at all.
109 accept_rate_number_title = _('%s has no accepted answers') % smart_unicode(user.username)
112 <span title="%(accept_rate_title)s" class="accept_rate">%(accept_rate_label)s:</span>
113 <span title="%(accept_rate_number_title)s">%(accept_rate)d%</span>
115 'accept_rate_label' : _('accept rate'),
116 'accept_rate_title' : _('Rate of the user\'s accepted answers'),
117 'accept_rate' : int(accept_rate),
118 'accept_rate_number_title' : u'%s' % accept_rate_number_title,
121 return mark_safe(html_output)
124 def get_age(birthday):
125 current_time = datetime.datetime(*time.localtime()[0:6])
127 month = birthday.month
129 diff = current_time - datetime.datetime(year, month, day, 0, 0, 0)
130 return diff.days / 365
133 def diff_date(date, limen=2):
137 now = datetime.datetime.now()
140 hours = int(diff.seconds/3600)
141 minutes = int(diff.seconds/60)
143 if date.year != now.year:
144 return dateformat.format(date, 'd M \'y, H:i')
146 return dateformat.format(date, 'd M, H:i')
149 return _('2 days ago')
151 return _('yesterday')
153 return ungettext('%(hr)d ' + _("hour ago"), '%(hr)d ' + _("hours ago"), hours) % {'hr':hours}
154 elif diff.seconds >= 60:
155 return ungettext('%(min)d ' + _("min ago"), '%(min)d ' + _("mins ago"), minutes) % {'min':minutes}
157 return ungettext('%(sec)d ' + _("sec ago"), '%(sec)d ' + _("secs ago"), diff.seconds) % {'sec':diff.seconds}
161 url = skins.find_media_source(url)
163 # Create the URL prefix.
164 url_prefix = settings.FORCE_SCRIPT_NAME + '/m/'
166 # Make sure any duplicate forward slashes are replaced with a single
168 url_prefix = re.sub("/+", "/", url_prefix)
170 url = url_prefix + url
174 def get_tag_font_size(tag):
175 occurrences_of_current_tag = tag.used_count
177 # Occurrences count settings
178 min_occurs = int(settings.TAGS_CLOUD_MIN_OCCURS)
179 max_occurs = int(settings.TAGS_CLOUD_MAX_OCCURS)
182 min_font_size = int(settings.TAGS_CLOUD_MIN_FONT_SIZE)
183 max_font_size = int(settings.TAGS_CLOUD_MAX_FONT_SIZE)
185 # Calculate the font size of the tag according to the occurrences count
186 weight = (math.log(occurrences_of_current_tag)-math.log(min_occurs))/(math.log(max_occurs)-math.log(min_occurs))
187 font_size_of_current_tag = min_font_size + int(math.floor((max_font_size-min_font_size)*weight))
189 return font_size_of_current_tag
191 class ItemSeparatorNode(template.Node):
192 def __init__(self, separator):
193 sep = separator.strip()
194 if sep[0] == sep[-1] and sep[0] in ('\'', '"'):
197 raise template.TemplateSyntaxError('separator in joinitems tag must be quoted')
200 def render(self, context):
203 class BlockMediaUrlNode(template.Node):
204 def __init__(self, nodelist):
205 self.items = nodelist
207 def render(self, context):
208 prefix = settings.APP_URL + 'm/'
212 for item in self.items:
213 url += item.render(context)
215 url = skins.find_media_source(url)
218 return out.replace(' ', '')
220 @register.tag(name='blockmedia')
221 def blockmedia(parser, token):
223 tagname = token.split_contents()
225 raise template.TemplateSyntaxError("blockmedia tag does not use arguments")
228 nodelist.append(parser.parse(('endblockmedia')))
229 next = parser.next_token()
230 if next.contents == 'endblockmedia':
232 return BlockMediaUrlNode(nodelist)
237 domain = settings.APP_BASE_URL
238 #protocol = getattr(settings, "PROTOCOL", "http")
240 return "%s%s" % (domain, path)
243 class SimpleVarNode(template.Node):
244 def __init__(self, name, value):
246 self.value = template.Variable(value)
248 def render(self, context):
249 context[self.name] = self.value.resolve(context)
252 class BlockVarNode(template.Node):
253 def __init__(self, name, block):
257 def render(self, context):
258 source = self.block.render(context)
259 context[self.name] = source.strip()
263 @register.tag(name='var')
264 def do_var(parser, token):
265 tokens = token.split_contents()[1:]
267 if not len(tokens) or not re.match('^\w+$', tokens[0]):
268 raise template.TemplateSyntaxError("Expected variable name")
271 nodelist = parser.parse(('endvar',))
272 parser.delete_first_token()
273 return BlockVarNode(tokens[0], nodelist)
274 elif len(tokens) == 3:
275 return SimpleVarNode(tokens[0], tokens[2])
277 raise template.TemplateSyntaxError("Invalid number of arguments")
279 class DeclareNode(template.Node):
280 dec_re = re.compile('^\s*(\w+)\s*(:?=)\s*(.*)$')
282 def __init__(self, block):
285 def render(self, context):
286 source = self.block.render(context)
288 for line in source.splitlines():
289 m = self.dec_re.search(line)
291 clist = list(context)
297 d['reverse'] = reverse
298 d['settings'] = settings
299 d['smart_str'] = smart_str
300 d['smart_unicode'] = smart_unicode
301 d['force_unicode'] = force_unicode
305 command = m.group(3).strip()
306 context[m.group(1).strip()] = eval(command, d)
308 logging.error("Error in declare tag, when evaluating: %s" % m.group(3).strip())
312 @register.tag(name='declare')
313 def do_declare(parser, token):
314 nodelist = parser.parse(('enddeclare',))
315 parser.delete_first_token()
316 return DeclareNode(nodelist)
318 # Usage: {% random 1 999 %}
319 # Generates random number in the template
320 class RandomNumberNode(template.Node):
321 # We get the limiting numbers
322 def __init__(self, int_from, int_to):
323 self.int_from = int(int_from)
324 self.int_to = int(int_to)
326 # We generate the random number using the standard python interface
327 def render(self, context):
328 return str(random.randint(self.int_from, self.int_to))
330 @register.tag(name="random")
331 def random_number(parser, token):
332 # Try to get the limiting numbers from the token
334 tag_name, int_from, int_to = token.split_contents()
336 # If we had no success -- raise an exception
337 raise template.TemplateSyntaxError, "%r tag requires exactly two arguments" % token.contents.split()[0]
339 # Call the random Node
340 return RandomNumberNode(int_from, int_to)