1 # -*- coding: utf-8 -*-
2 # This file is part of django-ssify, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See README.md for more information.
6 This module should only be used for debugging SSI statements.
8 Using SsiRenderMiddleware in production defeats the purpose of using SSI
9 in the first place, and is unsafe. You should use a proper webserver with SSI
10 support as a proxy (i.e. Nginx with ssi=on).
13 from __future__ import unicode_literals
16 from urllib.parse import urlparse
18 from urlparse import urlparse
19 from django.core.urlresolvers import resolve
20 from .cache import get_caches
22 from .conf import conf
25 SSI_SET = re.compile(r"<!--#set var='(?P<var>[^']+)' "
26 r"value='(?P<value>|\\\\|.*?[^\\](?:\\\\)*)'-->", re.S)
27 SSI_ECHO = re.compile(r"<!--#echo var='(?P<var>[^']+)' encoding='none'-->")
28 SSI_INCLUDE = re.compile(r"<!--#include (?:virtual|file)='(?P<path>[^']+)'-->")
29 SSI_IF = re.compile(r"(?P<header><!--#if expr='(?P<expr>[^']*)'-->)"
30 r"(?P<value>.*?)(?:<!--#else-->(?P<else>.*?))?"
31 r"<!--#endif-->", re.S)
33 SSI_VAR = re.compile(r"\$\{(?P<var>.+)\}") # TODO: escaped?
36 class SsiRenderMiddleware(object):
38 Emulates a webserver with SSI support.
40 This middleware should only be used for debugging purposes.
41 SsiMiddleware will enable it automatically, if SSIFY_RENDER setting
42 is set to True, so you don't normally need to include it in
45 If SSIFY_RENDER_VERBOSE setting is True, it will also leave some
46 information in HTML comments.
50 def _process_rendered_response(request, response):
51 """Recursively process SSI statements in the response."""
52 def ssi_include(match):
53 """Replaces SSI include with contents rendered by relevant view."""
54 path = process_value(match.group('path'))
56 for cache in get_caches():
57 content = cache.get(path)
58 if content is not None:
61 func, args, kwargs = resolve(path)
62 parsed = urlparse(path)
64 # Reuse the original request, but reset some attributes.
65 request.META['PATH_INFO'] = request.path_info = \
66 request.path = parsed.path
67 request.META['QUERY_STRING'] = parsed.query
68 request.ssi_vars_needed = {}
70 subresponse = func(request, *args, **kwargs)
71 # FIXME: we should deal directly with bytes here.
72 if subresponse.streaming:
73 content = b"".join(subresponse.streaming_content)
75 content = subresponse.content
76 content = process_content(content.decode('utf-8'))
77 if conf.RENDER_VERBOSE:
81 match.group(0).replace('<!--#', '<!--#end-'),
87 """Interprets SSI set statement."""
88 variables[match.group('var')] = match.group('value')
89 if conf.RENDER_VERBOSE:
95 """Interprets SSI echo, outputting the value of the variable."""
96 content = variables[match.group('var')]
97 if conf.RENDER_VERBOSE:
101 match.group(0).replace('<!--#', '<!--#end-'),
107 """Interprets SSI if statement."""
108 expr = process_value(match.group('expr'))
110 content = match.group('value')
112 content = match.group('else') or ''
113 if conf.RENDER_VERBOSE:
115 match.group('header'),
117 match.group('header').replace('<!--#', '<!--#end-'),
123 """Resolves ${var}-style variable reference."""
124 return variables[match.group('var')]
126 def process_value(content):
127 """Resolves any ${var}-style variable references in the content."""
128 return re.sub(SSI_VAR, ssi_var, content)
130 def process_content(content):
131 """Interprets SSI statements in the content."""
132 content = re.sub(SSI_SET, ssi_set, content)
133 content = re.sub(SSI_ECHO, ssi_echo, content)
134 content = re.sub(SSI_IF, ssi_if, content)
135 content = re.sub(SSI_INCLUDE, ssi_include, content)
139 response.content = process_content(
140 response.content.decode('utf-8')).encode('utf-8')
141 response['Content-Length'] = len(response.content)
143 def process_response(self, request, response):
144 """Support for unrendered responses."""
145 if response.streaming:
147 if hasattr(response, 'render') and callable(response.render):
148 response.add_post_render_callback(
149 lambda r: self._process_rendered_response(request, r)
152 self._process_rendered_response(request, response)