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="http://www.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' : 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)
144 if date.year == now.year:
145 return dateformat.format(date, 'd M, H:i')
147 return dateformat.format(date, 'd M \'y, H:i')
150 return _('2 days ago')
152 return _('yesterday')
154 return ungettext('%(hr)d ' + _("hour ago"), '%(hr)d ' + _("hours ago"), hours) % {'hr':hours}
155 elif diff.seconds >= 60:
156 return ungettext('%(min)d ' + _("min ago"), '%(min)d ' + _("mins ago"), minutes) % {'min':minutes}
158 return ungettext('%(sec)d ' + _("sec ago"), '%(sec)d ' + _("secs ago"), diff.seconds) % {'sec':diff.seconds}
162 url = skins.find_media_source(url)
164 # Create the URL prefix.
165 url_prefix = settings.FORCE_SCRIPT_NAME + '/m/'
167 # Make sure any duplicate forward slashes are replaced with a single
169 url_prefix = re.sub("/+", "/", url_prefix)
171 url = url_prefix + url
174 class ItemSeparatorNode(template.Node):
175 def __init__(self, separator):
176 sep = separator.strip()
177 if sep[0] == sep[-1] and sep[0] in ('\'', '"'):
180 raise template.TemplateSyntaxError('separator in joinitems tag must be quoted')
183 def render(self, context):
186 class BlockMediaUrlNode(template.Node):
187 def __init__(self, nodelist):
188 self.items = nodelist
190 def render(self, context):
191 prefix = settings.APP_URL + 'm/'
195 for item in self.items:
196 url += item.render(context)
198 url = skins.find_media_source(url)
201 return out.replace(' ', '')
203 @register.tag(name='blockmedia')
204 def blockmedia(parser, token):
206 tagname = token.split_contents()
208 raise template.TemplateSyntaxError("blockmedia tag does not use arguments")
211 nodelist.append(parser.parse(('endblockmedia')))
212 next = parser.next_token()
213 if next.contents == 'endblockmedia':
215 return BlockMediaUrlNode(nodelist)
220 domain = settings.APP_BASE_URL
221 #protocol = getattr(settings, "PROTOCOL", "http")
223 return "%s%s" % (domain, path)
226 class SimpleVarNode(template.Node):
227 def __init__(self, name, value):
229 self.value = template.Variable(value)
231 def render(self, context):
232 context[self.name] = self.value.resolve(context)
235 class BlockVarNode(template.Node):
236 def __init__(self, name, block):
240 def render(self, context):
241 source = self.block.render(context)
242 context[self.name] = source.strip()
246 @register.tag(name='var')
247 def do_var(parser, token):
248 tokens = token.split_contents()[1:]
250 if not len(tokens) or not re.match('^\w+$', tokens[0]):
251 raise template.TemplateSyntaxError("Expected variable name")
254 nodelist = parser.parse(('endvar',))
255 parser.delete_first_token()
256 return BlockVarNode(tokens[0], nodelist)
257 elif len(tokens) == 3:
258 return SimpleVarNode(tokens[0], tokens[2])
260 raise template.TemplateSyntaxError("Invalid number of arguments")
262 class DeclareNode(template.Node):
263 dec_re = re.compile('^\s*(\w+)\s*(:?=)\s*(.*)$')
265 def __init__(self, block):
268 def render(self, context):
269 source = self.block.render(context)
271 for line in source.splitlines():
272 m = self.dec_re.search(line)
274 clist = list(context)
280 d['reverse'] = reverse
281 d['smart_str'] = smart_str
282 d['smart_unicode'] = smart_unicode
283 d['force_unicode'] = force_unicode
287 command = m.group(3).strip()
288 logging.error(command)
289 context[m.group(1).strip()] = eval(command, d)
291 logging.error("Error in declare tag, when evaluating: %s" % m.group(3).strip())
295 @register.tag(name='declare')
296 def do_declare(parser, token):
297 nodelist = parser.parse(('enddeclare',))
298 parser.delete_first_token()
299 return DeclareNode(nodelist)
301 # Usage: {% random 1 999 %}
302 # Generates random number in the template
303 class RandomNumberNode(template.Node):
304 # We get the limiting numbers
305 def __init__(self, int_from, int_to):
306 self.int_from = int(int_from)
307 self.int_to = int(int_to)
309 # We generate the random number using the standard python interface
310 def render(self, context):
311 return str(random.randint(self.int_from, self.int_to))
313 @register.tag(name="random")
314 def random_number(parser, token):
315 # Try to get the limiting numbers from the token
317 tag_name, int_from, int_to = token.split_contents()
319 # If we had no success -- raise an exception
320 raise template.TemplateSyntaxError, "%r tag requires exactly two arguments" % token.contents.split()[0]
322 # Call the random Node
323 return RandomNumberNode(int_from, int_to)