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
43
"""An IVLE request object. This is presented to the IVLE apps as a way of
44
interacting with the web server and the dispatcher.
46
Request object attributes:
48
String. The request method (eg. 'GET', 'POST', etc)
50
String. The path portion of the URI.
52
String. Name of the application specified in the URL, or None.
54
String. The path specified in the URL *not including* the
55
application or the IVLE location prefix. eg. a URL of
56
"/ivle/files/joe/myfiles" has a path of "joe/myfiles".
58
User object. Details of the user who is currently logged in, or
61
storm.store.Store instance. Holds a database transaction open,
62
which is available for the entire lifetime of the request.
64
String. Hostname the server is running on.
66
Table object representing headers sent by the client.
67
headers_out (read, can be written to)
68
Table object representing headers to be sent to the client.
70
Bool. True if the request came for the "public host" as
71
configured in conf.py. Note that public mode requests do not
72
have an app (app is set to None).
75
Int. Response status number. Use one of the status codes defined
78
String. The Content-Type (mime type) header value.
80
String. Response "Location" header value. Used with HTTP redirect
83
List of strings. Write a list of URLs to CSS files here, and they
84
will be incorporated as <link rel="stylesheet" type="text/css">
85
elements in the head, if write_html_head_foot is True.
86
URLs should be relative to the IVLE root; they will be fixed up
89
List of strings. Write a list of URLs to JS files here, and they
90
will be incorporated as <script type="text/javascript"> elements
91
in the head, if write_html_head_foot is True.
92
URLs should be relative to the IVLE root; they will be fixed up
95
List of strings. Write a list of JS function names, and they
96
will be added as window.addListener('load', ..., false); calls
97
in the head, if write_html_head_foot is True.
98
This is the propper way to specify functions that need to run at
102
# Special code for an OK response.
103
# Do not use HTTP_OK; for some reason Apache produces an "OK" error
104
# message if you do that.
110
HTTP_SWITCHING_PROTOCOLS = 101
111
HTTP_PROCESSING = 102
115
HTTP_NON_AUTHORITATIVE = 203
116
HTTP_NO_CONTENT = 204
117
HTTP_RESET_CONTENT = 205
118
HTTP_PARTIAL_CONTENT = 206
119
HTTP_MULTI_STATUS = 207
120
HTTP_MULTIPLE_CHOICES = 300
121
HTTP_MOVED_PERMANENTLY = 301
122
HTTP_MOVED_TEMPORARILY = 302
124
HTTP_NOT_MODIFIED = 304
126
HTTP_TEMPORARY_REDIRECT = 307
127
HTTP_BAD_REQUEST = 400
128
HTTP_UNAUTHORIZED = 401
129
HTTP_PAYMENT_REQUIRED = 402
132
HTTP_METHOD_NOT_ALLOWED = 405
133
HTTP_NOT_ACCEPTABLE = 406
134
HTTP_PROXY_AUTHENTICATION_REQUIRED= 407
135
HTTP_REQUEST_TIME_OUT = 408
138
HTTP_LENGTH_REQUIRED = 411
139
HTTP_PRECONDITION_FAILED = 412
140
HTTP_REQUEST_ENTITY_TOO_LARGE = 413
141
HTTP_REQUEST_URI_TOO_LARGE = 414
142
HTTP_UNSUPPORTED_MEDIA_TYPE = 415
143
HTTP_RANGE_NOT_SATISFIABLE = 416
144
HTTP_EXPECTATION_FAILED = 417
145
HTTP_UNPROCESSABLE_ENTITY = 422
147
HTTP_FAILED_DEPENDENCY = 424
148
HTTP_INTERNAL_SERVER_ERROR = 500
149
HTTP_NOT_IMPLEMENTED = 501
150
HTTP_BAD_GATEWAY = 502
151
HTTP_SERVICE_UNAVAILABLE = 503
152
HTTP_GATEWAY_TIME_OUT = 504
153
HTTP_VERSION_NOT_SUPPORTED = 505
154
HTTP_VARIANT_ALSO_VARIES = 506
155
HTTP_INSUFFICIENT_STORAGE = 507
156
HTTP_NOT_EXTENDED = 510
158
def __init__(self, req, config):
159
"""Create an IVLE request from a mod_python one.
161
@param req: A mod_python request.
162
@param config: An IVLE configuration.
165
# Methods are mostly wrappers around the Apache request object
166
self.apache_req = req
168
self.headers_written = False
170
# Determine if the browser used the public host name to make the
171
# request (in which case we are in "public mode")
172
if req.hostname == config['urls']['public_host']:
173
self.publicmode = True
175
self.publicmode = False
177
# Inherit values for the input members
178
self.method = req.method
180
# Split the given path into the app (top-level dir) and sub-path
181
# (after first stripping away the root directory)
182
path = self.unmake_path(req.uri)
183
(self.app, self.path) = (ivle.util.split_path(path))
185
self.hostname = req.hostname
186
self.headers_in = req.headers_in
187
self.headers_out = req.headers_out
189
# Open a database connection and transaction, keep it around for users
190
# of the Request object to use
191
self.store = ivle.database.get_store(config)
193
# Default values for the output members
194
self.status = Request.HTTP_OK
195
self.content_type = None # Use Apache's default
199
self.scripts_init = []
200
# In some cases we don't want the template JS (such as the username
201
# and public FQDN) in the output HTML. In that case, set this to 0.
202
self.write_javascript_settings = True
203
self.got_common_vars = False
209
def __writeheaders(self):
210
"""Writes out the HTTP and HTML headers before any real data is
212
self.headers_written = True
214
# Prepare the HTTP and HTML headers before the first write is made
215
if self.content_type != None:
216
self.apache_req.content_type = self.content_type
217
self.apache_req.status = self.status
218
if self.location != None:
219
self.apache_req.headers_out['Location'] = self.location
221
def ensure_headers_written(self):
222
"""Writes out the HTTP and HTML headers if they haven't already been
224
if not self.headers_written:
225
self.__writeheaders()
227
def write(self, string, flush=1):
228
"""Writes string directly to the client, then flushes the buffer,
229
unless flush is 0."""
231
if not self.headers_written:
232
self.__writeheaders()
233
if isinstance(string, unicode):
234
# Encode unicode strings as UTF-8
235
# (Otherwise cannot handle being written to a bytestream)
236
self.apache_req.write(string.encode('utf8'), flush)
238
# 8-bit clean strings just get written directly.
239
# This includes binary strings.
240
self.apache_req.write(string, flush)
243
"""Log out the current user by destroying the session state.
244
Then redirect to the top-level IVLE page."""
245
if hasattr(self, 'session'):
246
self.session.invalidate()
247
self.session.delete()
248
# Invalidates all IVLE cookies
249
all_cookies = mod_python.Cookie.get_cookies(self)
251
# Create cookies for plugins that might request them.
252
for plugin in self.config.plugin_index[CookiePlugin]:
253
for cookie in plugin.cookies:
254
self.add_cookie(mod_python.Cookie.Cookie(cookie, '',
255
expires=1, path='/'))
256
self.throw_redirect(self.make_path(''))
260
"""Flushes the output buffer."""
261
self.apache_req.flush()
263
def sendfile(self, filename):
264
"""Sends the named file directly to the client."""
265
if not self.headers_written:
266
self.__writeheaders()
267
self.apache_req.sendfile(filename)
269
def read(self, len=None):
270
"""Reads at most len bytes directly from the client. (See mod_python
273
return self.apache_req.read()
275
return self.apache_req.read(len)
277
def throw_redirect(self, location):
278
"""Writes out an HTTP redirect to the specified URL. Raises an
279
exception which is caught by the dispatch or web server, so any
280
code following this call will not be executed.
282
httpcode: An HTTP response status code. Pass a constant from the
285
# Note: location may be a unicode, but it MUST only have ASCII
286
# characters (non-ascii characters should be URL-encoded).
287
mod_python.util.redirect(self.apache_req, location.encode("ascii"))
289
def add_cookie(self, cookie, value=None, **attributes):
290
"""Inserts a cookie into this request object's headers."""
292
mod_python.Cookie.add_cookie(self.apache_req, cookie)
294
mod_python.Cookie.add_cookie(self.apache_req, cookie, value, **attributes)
296
def make_path(self, path):
297
"""Prepend the IVLE URL prefix to the given path.
299
This is used when generating URLs to send to the client.
301
This method is DEPRECATED. We no longer support use of a prefix.
303
return os.path.join(self.config['urls']['root'], path)
305
def unmake_path(self, path):
306
"""Strip the IVLE URL prefix from the given path, if present.
308
Also normalises the path.
310
This method is DEPRECATED. We no longer support use of a prefix.
312
path = os.path.normpath(path)
313
root = os.path.normpath(self.config['urls']['root'])
315
if path.startswith(root):
316
path = path[len(root):]
317
# Take out the slash as well
318
if len(path) > 0 and path[0] == os.sep:
323
def get_session(self):
324
"""Returns a mod_python Session object for this request.
325
Note that this is dependent on mod_python and may need to change
326
interface if porting away from mod_python.
328
IMPORTANT: Call unlock() on the session as soon as you are done with
329
it! If you don't, all other requests will block!
331
# Cache the session object and set the timeout to 24 hours.
332
if not hasattr(self, 'session'):
333
self.session = mod_python.Session.FileSession(self.apache_req,
334
timeout = 60 * 60 * 24)
337
def get_fieldstorage(self):
338
"""Returns a mod_python FieldStorage object for this request.
339
Note that this is dependent on mod_python and may need to change
340
interface if porting away from mod_python."""
341
# Cache the fieldstorage object
342
if not hasattr(self, 'fields'):
343
self.fields = mod_python.util.FieldStorage(self.apache_req)
346
def get_cgi_environ(self):
347
"""Returns the CGI environment emulation for this request. (Calls
348
add_common_vars). The environment is returned as a mapping
349
compatible with os.environ."""
350
if not self.got_common_vars:
351
self.apache_req.add_common_vars()
352
self.got_common_vars = True
353
return self.apache_req.subprocess_env
356
def get_http_codename(code):
357
"""Given a HTTP error code int, returns a (name, description)
358
pair, suitable for displaying to the user.
359
May return (None,None) if code is unknown.
360
Only lists common 4xx and 5xx codes (since this is just used
361
to display throw_error error messages).
364
return http_codenames[code]
368
# Human strings for HTTP response codes
370
Request.HTTP_BAD_REQUEST:
372
"Your browser sent a request IVLE did not understand."),
373
Request.HTTP_UNAUTHORIZED:
375
"You are not allowed to view this part of IVLE."),
376
Request.HTTP_FORBIDDEN:
378
"You are not allowed to view this part of IVLE."),
379
Request.HTTP_NOT_FOUND:
381
"The application or file you requested does not exist."),
382
Request.HTTP_METHOD_NOT_ALLOWED:
383
("Method Not Allowed",
384
"Your browser is interacting with IVLE in the wrong way."
385
"This is probably a bug in IVLE. "
386
"Please report it to the administrators."),
387
Request.HTTP_INTERNAL_SERVER_ERROR:
388
("Internal Server Error",
389
"An unknown error occured in IVLE."),
390
Request.HTTP_NOT_IMPLEMENTED:
392
"The application or file you requested has not been implemented "
394
Request.HTTP_SERVICE_UNAVAILABLE:
395
("Service Unavailable",
396
"IVLE is currently experiencing technical difficulties. "
397
"Please try again later."),