1 from django.utils.translation import ugettext_lazy as _
2 from django.core.validators import RegexValidator
3 from django.core.exceptions import ValidationError
4 from django.template import Template, Parser, Lexer, TOKEN_BLOCK, TOKEN_VAR, TemplateSyntaxError
5 from django.utils import simplejson as json
6 from django.utils.html import escape, mark_safe
8 from philo.utils import LOADED_TEMPLATE_ATTR
19 class RedirectValidator(RegexValidator):
20 """Based loosely on the URLValidator, but no option to verify_exists"""
22 r'^(?:https?://' # http:// or https://
23 r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?|' #domain...
24 r'localhost|' #localhost...
25 r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
26 r'(?::\d+)?' # optional port
30 message = _(u'Enter a valid absolute or relative redirect target')
33 class URLLinkValidator(RegexValidator):
34 """Based loosely on the URLValidator, but no option to verify_exists"""
36 r'^(?:https?://' # http:// or https://
37 r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?|' #domain...
38 r'localhost|' #localhost...
39 r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
40 r'(?::\d+)?' # optional port
41 r'|)' # also allow internal links
42 r'(?:/?|[/?#]?\S+)$', re.IGNORECASE)
43 message = _(u'Enter a valid absolute or relative redirect target')
46 def json_validator(value):
50 raise ValidationError(u'JSON decode error: %s' % e)
53 class TemplateValidationParser(Parser):
54 def __init__(self, tokens, allow=None, disallow=None, secure=True):
55 super(TemplateValidationParser, self).__init__(tokens)
57 allow, disallow = set(allow or []), set(disallow or [])
60 disallow |= set(INSECURE_TAGS)
62 self.allow, self.disallow, self.secure = allow, disallow, secure
64 def parse(self, parse_until=None):
65 if parse_until is None:
68 nodelist = self.create_nodelist()
70 token = self.next_token()
71 # We only need to parse var and block tokens.
72 if token.token_type == TOKEN_VAR:
73 if not token.contents:
74 self.empty_variable(token)
76 filter_expression = self.compile_filter(token.contents)
77 var_node = self.create_variable_node(filter_expression)
78 self.extend_nodelist(nodelist, var_node,token)
79 elif token.token_type == TOKEN_BLOCK:
80 if token.contents in parse_until:
81 # put token back on token list so calling code knows why it terminated
82 self.prepend_token(token)
86 command = token.contents.split()[0]
88 self.empty_block_tag(token)
90 if (self.allow and command not in self.allow) or (self.disallow and command in self.disallow):
91 self.disallowed_tag(command)
93 self.enter_command(command, token)
96 compile_func = self.tags[command]
98 self.invalid_block_tag(token, command, parse_until)
101 compiled_result = compile_func(self, token)
102 except TemplateSyntaxError, e:
103 if not self.compile_function_error(token, e):
106 self.extend_nodelist(nodelist, compiled_result, token)
110 self.unclosed_block_tag(parse_until)
114 def disallowed_tag(self, command):
115 if self.secure and command in INSECURE_TAGS:
116 raise ValidationError('Tag "%s" is not permitted for security reasons.' % command)
117 raise ValidationError('Tag "%s" is not permitted here.' % command)
120 def linebreak_iter(template_source):
121 # Cribbed from django/views/debug.py
123 p = template_source.find('\n')
126 p = template_source.find('\n', p+1)
127 yield len(template_source) + 1
130 class TemplateValidator(object):
131 def __init__(self, allow=None, disallow=None, secure=True):
133 self.disallow = disallow
136 def __call__(self, value):
138 self.validate_template(value)
139 except ValidationError:
142 if hasattr(e, 'source') and isinstance(e, TemplateSyntaxError):
143 origin, (start, end) = e.source
144 template_source = origin.reload()
146 for num, next in enumerate(linebreak_iter(template_source)):
147 if start >= upto and end <= next:
148 raise ValidationError(mark_safe("Template code invalid: \"%s\" (%s:%d).<br />%s" % (escape(template_source[start:end]), origin.loadname, num, e)))
150 raise ValidationError("Template code invalid. Error was: %s: %s" % (e.__class__.__name__, e))
152 def validate_template(self, template_string):
153 # We want to tokenize like normal, then use a custom parser.
154 lexer = Lexer(template_string, None)
155 tokens = lexer.tokenize()
156 parser = TemplateValidationParser(tokens, self.allow, self.disallow, self.secure)
158 for node in parser.parse():
159 template = getattr(node, LOADED_TEMPLATE_ATTR, None)