1
# IVLE - Informatics Virtual Learning Environment
2
# Copyright (C) 2007-2009 The University of Melbourne
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
# GNU General Public License for more details.
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
23
Builds an IVLE request object from a mod_python request object.
24
See design notes/apps/dispatch.txt for a full specification of this request
29
import mod_python.Session
30
import mod_python.Cookie
31
import mod_python.util
33
# This needs to be importable from outside Apache.
40
from ivle.webapp.base.plugins import CookiePlugin
41
import ivle.webapp.security
44
"""An IVLE request object. This is presented to the IVLE apps as a way of
45
interacting with the web server and the dispatcher.
47
Request object attributes:
49
String. The request method (eg. 'GET', 'POST', etc)
51
String. The path portion of the URI.
53
String. Name of the application specified in the URL, or None.
55
String. The path specified in the URL *not including* the
56
application or the IVLE location prefix. eg. a URL of
57
"/ivle/files/joe/myfiles" has a path of "joe/myfiles".
59
User object. Details of the user who is currently logged in, or
62
storm.store.Store instance. Holds a database transaction open,
63
which is available for the entire lifetime of the request.
65
String. Hostname the server is running on.
67
Table object representing headers sent by the client.
68
headers_out (read, can be written to)
69
Table object representing headers to be sent to the client.
71
Bool. True if the request came for the "public host" as
72
configured in conf.py. Note that public mode requests do not
73
have an app (app is set to None).
76
Int. Response status number. Use one of the status codes defined
79
String. The Content-Type (mime type) header value.
81
String. Response "Location" header value. Used with HTTP redirect
85
# Special code for an OK response.
86
# Do not use HTTP_OK; for some reason Apache produces an "OK" error
87
# message if you do that.
93
HTTP_MOVED_TEMPORARILY = 302
96
HTTP_INTERNAL_SERVER_ERROR = 500
100
def __init__(self, req, config):
101
"""Create an IVLE request from a mod_python one.
103
@param req: A mod_python request.
104
@param config: An IVLE configuration.
107
# Methods are mostly wrappers around the Apache request object
108
self.apache_req = req
110
self.headers_written = False
112
# Determine if the browser used the public host name to make the
113
# request (in which case we are in "public mode")
114
if req.hostname == config['urls']['public_host']:
115
self.publicmode = True
117
self.publicmode = False
119
# Inherit values for the input members
120
self.method = req.method
122
# Split the given path into the app (top-level dir) and sub-path
123
# (after first stripping away the root directory)
124
(self.app, self.path) = (ivle.util.split_path(req.uri))
125
self.hostname = req.hostname
126
self.headers_in = req.headers_in
127
self.headers_out = req.headers_out
129
# Default values for the output members
130
self.status = Request.HTTP_OK
131
self.content_type = None # Use Apache's default
133
# In some cases we don't want the template JS (such as the username
134
# and public FQDN) in the output HTML. In that case, set this to 0.
135
self.write_javascript_settings = True
136
self.got_common_vars = False
143
if self._store is not None:
149
if self._store is not None:
152
def __writeheaders(self):
153
"""Writes out the HTTP and HTML headers before any real data is
155
self.headers_written = True
157
# Prepare the HTTP and HTML headers before the first write is made
158
if self.content_type != None:
159
self.apache_req.content_type = self.content_type
160
self.apache_req.status = self.status
161
if self.location != None:
162
self.apache_req.headers_out['Location'] = self.location
164
def ensure_headers_written(self):
165
"""Writes out the HTTP and HTML headers if they haven't already been
167
if not self.headers_written:
168
self.__writeheaders()
170
def write(self, string, flush=1):
171
"""Writes string directly to the client, then flushes the buffer,
172
unless flush is 0."""
174
if not self.headers_written:
175
self.__writeheaders()
176
if isinstance(string, unicode):
177
# Encode unicode strings as UTF-8
178
# (Otherwise cannot handle being written to a bytestream)
179
self.apache_req.write(string.encode('utf8'), flush)
181
# 8-bit clean strings just get written directly.
182
# This includes binary strings.
183
self.apache_req.write(string, flush)
186
"""Log out the current user by destroying the session state.
187
Then redirect to the top-level IVLE page."""
188
if hasattr(self, 'session'):
189
self.session.invalidate()
190
self.session.delete()
191
# Invalidates all IVLE cookies
192
all_cookies = mod_python.Cookie.get_cookies(self)
194
# Create cookies for plugins that might request them.
195
for plugin in self.config.plugin_index[CookiePlugin]:
196
for cookie in plugin.cookies:
197
self.add_cookie(mod_python.Cookie.Cookie(cookie, '',
198
expires=1, path='/'))
199
self.throw_redirect(self.make_path(''))
203
"""Flushes the output buffer."""
204
self.apache_req.flush()
206
def sendfile(self, filename):
207
"""Sends the named file directly to the client."""
208
if not self.headers_written:
209
self.__writeheaders()
210
self.apache_req.sendfile(filename)
212
def read(self, len=None):
213
"""Reads at most len bytes directly from the client. (See mod_python
216
return self.apache_req.read()
218
return self.apache_req.read(len)
220
def throw_redirect(self, location):
221
"""Writes out an HTTP redirect to the specified URL. Raises an
222
exception which is caught by the dispatch or web server, so any
223
code following this call will not be executed.
225
httpcode: An HTTP response status code. Pass a constant from the
228
# Note: location may be a unicode, but it MUST only have ASCII
229
# characters (non-ascii characters should be URL-encoded).
230
mod_python.util.redirect(self.apache_req, location.encode("ascii"))
232
def add_cookie(self, cookie, value=None, **attributes):
233
"""Inserts a cookie into this request object's headers."""
235
mod_python.Cookie.add_cookie(self.apache_req, cookie)
237
mod_python.Cookie.add_cookie(self.apache_req, cookie, value, **attributes)
239
def make_path(self, path):
240
"""Prepend the IVLE URL prefix to the given path.
242
This is used when generating URLs to send to the client.
244
This method is DEPRECATED. We no longer support use of a prefix.
246
return os.path.join(self.config['urls']['root'], path)
248
def get_session(self):
249
"""Returns a mod_python Session object for this request.
250
Note that this is dependent on mod_python and may need to change
251
interface if porting away from mod_python.
253
IMPORTANT: Call unlock() on the session as soon as you are done with
254
it! If you don't, all other requests will block!
256
# Cache the session object and set the timeout to 24 hours.
257
if not hasattr(self, 'session'):
258
self.session = mod_python.Session.FileSession(self.apache_req,
259
timeout = 60 * 60 * 24)
262
def get_fieldstorage(self):
263
"""Returns a mod_python FieldStorage object for this request.
264
Note that this is dependent on mod_python and may need to change
265
interface if porting away from mod_python."""
266
# Cache the fieldstorage object
267
if not hasattr(self, 'fields'):
268
self.fields = mod_python.util.FieldStorage(self.apache_req)
271
def get_cgi_environ(self):
272
"""Returns the CGI environment emulation for this request. (Calls
273
add_common_vars). The environment is returned as a mapping
274
compatible with os.environ."""
275
if not self.got_common_vars:
276
self.apache_req.add_common_vars()
277
self.got_common_vars = True
278
return self.apache_req.subprocess_env
282
# Open a database connection and transaction, keep it around for users
283
# of the Request object to use.
284
if self._store is None:
285
self._store = ivle.database.get_store(self.config)
290
# Get and cache the request user, or None if it's not valid.
291
# This is a property so that we don't create a store unless
292
# some code actually requests the user.
295
except AttributeError:
299
temp_user = ivle.webapp.security.get_user_details(self)
300
if temp_user and temp_user.valid:
301
self._user = temp_user