import math import random from django import template from django.conf import settings register = template.Library() class ObfuscateNode(template.Node): def __init__(self, email, display=None, title=None): self.email = email self.display = display self.title = title def render(self, context): if isinstance(self.email, template.FilterExpression): self.email = self.email.resolve(context).lower() if isinstance(self.title, template.FilterExpression): self.title = self.title.resolve(context) if isinstance(self.display, template.FilterExpression): self.display = self.display.resolve(context) coded = "" unmixedkey = u"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.@" inprogresskey = unmixedkey mixedkey = "" unshuffled = len(unmixedkey) for i in range(len(unmixedkey)): pos = int(math.ceil(random.random() * (unshuffled - 1))) nextchar = inprogresskey[pos] mixedkey += nextchar before = inprogresskey[0:pos] after = inprogresskey[pos + 1:] inprogresskey = before + after unshuffled -= 1 cipher = mixedkey shift = len(self.email) for j in range(len(self.email)): if cipher.find(self.email[j]) == -1 : chr = self.email[j] coded += self.email[j] else : chr = (cipher.find(self.email[j]) + shift) % len(cipher) coded += cipher[chr] txt = "" return txt def do_obfuscate(parser, token): """ Email link and general text obfuscator If link.title is provided an HTML link is created {% obfuscate link.email link.title %} """ args = token.split_contents() tag = args[0] if len(args) not in (2, 3, 4): raise template.TemplateSyntaxError("Invalid syntax. Expected \ '{%% %s 'text' %%} or '\ '{%% %s 'email' 'title' %%} or '\ '{%% %s 'email' 'title' 'innertext' %%}'" % (tag, tag, tag)) if (args[1][0] == args[1][-1] and args[1][0] in ('"', "'")): email = args[1][1:-1] else: email = parser.compile_filter(args[1]) title, display = None, None if len(args) >= 3: if (args[2][0] == args[2][-1] and args[2][0] in ('"', "'")): title = args[2][1:-1] else: title = parser.compile_filter(args[2]) if len(args) >= 4: if (args[3][0] == args[3][-1] and args[3][0] in ('"', "'")): display = args[3][1:-1] else: display = parser.compile_filter(args[3]) return ObfuscateNode(email, display=display, title=title) register.tag('obfuscate', do_obfuscate)