Add separate version file.
[django-ssify.git] / ssify / middleware_debug.py
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.
4 #
5 """
6 This module should only be used for debugging SSI statements.
7
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).
11
12 """
13 from __future__ import unicode_literals
14 import re
15 try:
16     from urllib.parse import urlparse
17 except ImportError:
18     from urlparse import urlparse
19 from django.core.urlresolvers import resolve
20 from .cache import get_caches
21
22 from .conf import conf
23
24
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)
32         # TODO: escaped?
33 SSI_VAR = re.compile(r"\$\{(?P<var>.+)\}")  # TODO: escaped?
34
35
36 class SsiRenderMiddleware(object):
37     """
38     Emulates a webserver with SSI support.
39
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
43     MIDDLEWARE_CLASSES.
44
45     If SSIFY_RENDER_VERBOSE setting is True, it will also leave some
46     information in HTML comments.
47
48     """
49     @staticmethod
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'))
55             content = None
56             for cache in get_caches():
57                 content = cache.get(path)
58                 if content is not None:
59                     break
60             if content is None:
61                 func, args, kwargs = resolve(path)
62                 parsed = urlparse(path)
63
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 = {}
69
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)
74                 else:
75                     content = subresponse.content
76             content = process_content(content.decode('utf-8'))
77             if conf.RENDER_VERBOSE:
78                 return "".join((
79                     match.group(0),
80                     content,
81                     match.group(0).replace('<!--#', '<!--#end-'),
82                 ))
83             else:
84                 return content
85
86         def ssi_set(match):
87             """Interprets SSI set statement."""
88             variables[match.group('var')] = match.group('value')
89             if conf.RENDER_VERBOSE:
90                 return match.group(0)
91             else:
92                 return ""
93
94         def ssi_echo(match):
95             """Interprets SSI echo, outputting the value of the variable."""
96             content = variables[match.group('var')]
97             if conf.RENDER_VERBOSE:
98                 return "".join((
99                     match.group(0),
100                     content,
101                     match.group(0).replace('<!--#', '<!--#end-'),
102                 ))
103             else:
104                 return content
105
106         def ssi_if(match):
107             """Interprets SSI if statement."""
108             expr = process_value(match.group('expr'))
109             if expr:
110                 content = match.group('value')
111             else:
112                 content = match.group('else') or ''
113             if conf.RENDER_VERBOSE:
114                 return "".join((
115                     match.group('header'),
116                     content,
117                     match.group('header').replace('<!--#', '<!--#end-'),
118                 ))
119             else:
120                 return content
121
122         def ssi_var(match):
123             """Resolves ${var}-style variable reference."""
124             return variables[match.group('var')]
125
126         def process_value(content):
127             """Resolves any ${var}-style variable references in the content."""
128             return re.sub(SSI_VAR, ssi_var, content)
129
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)
136             return content
137
138         variables = {}
139         response.content = process_content(
140             response.content.decode('utf-8')).encode('utf-8')
141         response['Content-Length'] = len(response.content)
142
143     def process_response(self, request, response):
144         """Support for unrendered responses."""
145         if response.streaming:
146             return response
147         if hasattr(response, 'render') and callable(response.render):
148             response.add_post_render_callback(
149                 lambda r: self._process_rendered_response(request, r)
150             )
151         else:
152             self._process_rendered_response(request, response)
153         return response