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 # If the Show Accept Rate feature is not activated this tag should return a blank string
86 if not settings.SHOW_USER_ACCEPT_RATE:
89 # We get the number of all user's answers.
90 total_answers_count = Answer.objects.filter(author=user).count()
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()
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.
98 accept_rate = (float(accepted_answers_count) / float(total_answers_count) * 100)
99 except ZeroDivisionError:
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)
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.
113 accept_rate_number_title = _('%s has no accepted answers') % smart_unicode(user.username)
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%</span>
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,
125 return mark_safe(html_output)
128 def get_age(birthday):
129 current_time = datetime.datetime(*time.localtime()[0:6])
131 month = birthday.month
133 diff = current_time - datetime.datetime(year, month, day, 0, 0, 0)
134 return diff.days / 365
137 def diff_date(date, limen=2):
141 now = datetime.datetime.now()
144 hours = int(diff.seconds/3600)
145 minutes = int(diff.seconds/60)
147 if date.year != now.year:
148 return dateformat.format(date, 'd M \'y, H:i')
150 return dateformat.format(date, 'd M, H:i')
153 return _('2 days ago')
155 return _('yesterday')
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}
161 return ungettext('%(sec)d ' + _("sec ago"), '%(sec)d ' + _("secs ago"), diff.seconds) % {'sec':diff.seconds}
165 url = skins.find_media_source(url)
167 # Create the URL prefix.
168 url_prefix = settings.FORCE_SCRIPT_NAME + '/m/'
170 # Make sure any duplicate forward slashes are replaced with a single
172 url_prefix = re.sub("/+", "/", url_prefix)
174 url = url_prefix + url
178 def get_tag_font_size(tag):
179 occurrences_of_current_tag = tag.used_count
181 # Occurrences count settings
182 min_occurs = int(settings.TAGS_CLOUD_MIN_OCCURS)
183 max_occurs = int(settings.TAGS_CLOUD_MAX_OCCURS)
186 min_font_size = int(settings.TAGS_CLOUD_MIN_FONT_SIZE)
187 max_font_size = int(settings.TAGS_CLOUD_MAX_FONT_SIZE)
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))
193 return font_size_of_current_tag
195 class ItemSeparatorNode(template.Node):
196 def __init__(self, separator):
197 sep = separator.strip()
198 if sep[0] == sep[-1] and sep[0] in ('\'', '"'):
201 raise template.TemplateSyntaxError('separator in joinitems tag must be quoted')
204 def render(self, context):
207 class BlockMediaUrlNode(template.Node):
208 def __init__(self, nodelist):
209 self.items = nodelist
211 def render(self, context):
212 prefix = settings.APP_URL + 'm/'
216 for item in self.items:
217 url += item.render(context)
219 url = skins.find_media_source(url)
222 return out.replace(' ', '')
224 @register.tag(name='blockmedia')
225 def blockmedia(parser, token):
227 tagname = token.split_contents()
229 raise template.TemplateSyntaxError("blockmedia tag does not use arguments")
232 nodelist.append(parser.parse(('endblockmedia')))
233 next = parser.next_token()
234 if next.contents == 'endblockmedia':
236 return BlockMediaUrlNode(nodelist)
241 domain = settings.APP_BASE_URL
242 #protocol = getattr(settings, "PROTOCOL", "http")
244 return "%s%s" % (domain, path)
247 class SimpleVarNode(template.Node):
248 def __init__(self, name, value):
250 self.value = template.Variable(value)
252 def render(self, context):
253 context[self.name] = self.value.resolve(context)
256 class BlockVarNode(template.Node):
257 def __init__(self, name, block):
261 def render(self, context):
262 source = self.block.render(context)
263 context[self.name] = source.strip()
267 @register.tag(name='var')
268 def do_var(parser, token):
269 tokens = token.split_contents()[1:]
271 if not len(tokens) or not re.match('^\w+$', tokens[0]):
272 raise template.TemplateSyntaxError("Expected variable name")
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])
281 raise template.TemplateSyntaxError("Invalid number of arguments")
283 class DeclareNode(template.Node):
284 dec_re = re.compile('^\s*(\w+)\s*(:?=)\s*(.*)$')
286 def __init__(self, block):
289 def render(self, context):
290 source = self.block.render(context)
292 for line in source.splitlines():
293 m = self.dec_re.search(line)
295 clist = list(context)
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
309 command = m.group(3).strip()
310 context[m.group(1).strip()] = eval(command, d)
312 logging.error("Error in declare tag, when evaluating: %s" % m.group(3).strip())
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)
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)
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))
333 @register.tag(name="random")
334 def random_number(parser, token):
335 # Try to get the limiting numbers from the token
337 tag_name, int_from, int_to = token.split_contents()
339 # If we had no success -- raise an exception
340 raise template.TemplateSyntaxError, "%r tag requires exactly two arguments" % token.contents.split()[0]
342 # Call the random Node
343 return RandomNumberNode(int_from, int_to)