# combo - content management system # Copyright (C) 2015-2018 Entr'ouvert # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . import re from django.conf import settings from django.utils.encoding import force_text from django.template import Context, Template, TemplateSyntaxError, VariableDoesNotExist from django.utils.http import quote class TemplateError(Exception): def __init__(self, msg, params=()): self.msg = msg self.params = params def __str__(self): return self.msg % self.params def get_templated_url(url, context=None): if '{{' not in url and '{%' not in url and '[' not in url: return url template_vars = Context(use_l10n=False) if context: if hasattr(context, 'flatten'): # it's a django Context, dictionarize it: context = context.flatten() template_vars.update(context) template_vars['user_email'] = '' template_vars['user_nameid'] = '' user = getattr(context.get('request'), 'user', None) if user and user.is_authenticated: template_vars['user_email'] = quote(user.email) user_nameid = user.get_name_id() if user_nameid: template_vars['user_nameid'] = quote(user_nameid) template_vars.update(settings.TEMPLATE_VARS) if '{{' in url or '{%' in url: # Django template try: return Template(url).render(template_vars) except VariableDoesNotExist as e: raise TemplateError(e.msg, e.params) except TemplateSyntaxError: raise TemplateError('syntax error') # ezt-like template def repl(matchobj): varname = matchobj.group(0)[1:-1] if varname == '[': return '[' if varname not in template_vars: raise TemplateError('unknown variable %s', varname) return force_text(template_vars[varname]) return re.sub(r'(\[.+?\])', repl, url)