~azzar1/unity/add-show-desktop-key

« back to all changes in this revision

Viewing changes to www/dispatch/request.py

  • Committer: mattgiuca
  • Date: 2008-07-15 07:19:34 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:875
Added "migrations" directory, which contains incremental database update
    scripts.
Updated users.sql, uniqueness key on offering table.
Added migration matching this update to the migrations directory. Mm handy!

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# IVLE - Informatics Virtual Learning Environment
 
2
# Copyright (C) 2007-2008 The University of Melbourne
 
3
#
 
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.
 
8
#
 
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.
 
13
#
 
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
 
17
 
 
18
# Module: dispatch.request
 
19
# Author: Matt Giuca
 
20
# Date:   12/12/2007
 
21
 
 
22
# Builds an IVLE request object from a mod_python request object.
 
23
# See design notes/apps/dispatch.txt for a full specification of this request
 
24
# object.
 
25
 
 
26
import common.util
 
27
import mod_python
 
28
from mod_python import (util, Session, Cookie)
 
29
import conf
 
30
 
 
31
class Request:
 
32
    """An IVLE request object. This is presented to the IVLE apps as a way of
 
33
    interacting with the web server and the dispatcher.
 
34
 
 
35
    Request object attributes:
 
36
        method (read)
 
37
            String. The request method (eg. 'GET', 'POST', etc)
 
38
        uri (read)
 
39
            String. The path portion of the URI.
 
40
        app (read)
 
41
            String. Name of the application specified in the URL, or None.
 
42
        path (read)
 
43
            String. The path specified in the URL *not including* the
 
44
            application or the IVLE location prefix. eg. a URL of
 
45
            "/ivle/files/joe/myfiles" has a path of "joe/myfiles".
 
46
        user (read)
 
47
            User object. Details of the user who is currently logged in, or
 
48
            None.
 
49
        hostname (read)
 
50
            String. Hostname the server is running on.
 
51
        headers_in (read)
 
52
            Table object representing headers sent by the client.
 
53
        headers_out (read, can be written to)
 
54
            Table object representing headers to be sent to the client.
 
55
        publicmode (read)
 
56
            Bool. True if the request came for the "public host" as
 
57
            configured in conf.py. Note that public mode requests do not
 
58
            have an app (app is set to None).
 
59
 
 
60
        status (write)
 
61
            Int. Response status number. Use one of the status codes defined
 
62
            in class Request.
 
63
        content_type (write)
 
64
            String. The Content-Type (mime type) header value.
 
65
        location (write)
 
66
            String. Response "Location" header value. Used with HTTP redirect
 
67
            responses.
 
68
        title (write)
 
69
            String. HTML page title. Used if write_html_head_foot is True, in
 
70
            the HTML title element text.
 
71
        styles (write)
 
72
            List of strings. Write a list of URLs to CSS files here, and they
 
73
            will be incorporated as <link rel="stylesheet" type="text/css">
 
74
            elements in the head, if write_html_head_foot is True.
 
75
            URLs should be relative to the IVLE root; they will be fixed up
 
76
            to be site-relative.
 
77
        scripts (write)
 
78
            List of strings. Write a list of URLs to JS files here, and they
 
79
            will be incorporated as <script type="text/javascript"> elements
 
80
            in the head, if write_html_head_foot is True.
 
81
            URLs should be relative to the IVLE root; they will be fixed up
 
82
            to be site-relative.
 
83
        scripts_init (write)
 
84
            List of strings. Write a list of JS function names, and they
 
85
            will be added as window.addListener('load', ..., false); calls
 
86
            in the head, if write_html_head_foot is True.
 
87
            This is the propper way to specify functions that need to run at 
 
88
            page load time.
 
89
        write_html_head_foot (write)
 
90
            Boolean. If True, dispatch assumes that this is an XHTML page, and
 
91
            will immediately write a full HTML head, open the body element,
 
92
            and write heading contents to the page, before any bytes are
 
93
            written. It will then write footer contents and close the body and
 
94
            html elements at the end of execution.  
 
95
 
 
96
            This value should be set to true by all applications for all HTML
 
97
            output (unless there is a good reason, eg. exec). The
 
98
            applications should therefore output HTML content assuming that
 
99
            it will be written inside the body tag. Do not write opening or
 
100
            closing <html> or <body> tags.
 
101
    """
 
102
 
 
103
    # Special code for an OK response.
 
104
    # Do not use HTTP_OK; for some reason Apache produces an "OK" error
 
105
    # message if you do that.
 
106
    OK  = 0
 
107
 
 
108
    # HTTP status codes
 
109
 
 
110
    HTTP_CONTINUE                     = 100
 
111
    HTTP_SWITCHING_PROTOCOLS          = 101
 
112
    HTTP_PROCESSING                   = 102
 
113
    HTTP_OK                           = 200
 
114
    HTTP_CREATED                      = 201
 
115
    HTTP_ACCEPTED                     = 202
 
116
    HTTP_NON_AUTHORITATIVE            = 203
 
117
    HTTP_NO_CONTENT                   = 204
 
118
    HTTP_RESET_CONTENT                = 205
 
119
    HTTP_PARTIAL_CONTENT              = 206
 
120
    HTTP_MULTI_STATUS                 = 207
 
121
    HTTP_MULTIPLE_CHOICES             = 300
 
122
    HTTP_MOVED_PERMANENTLY            = 301
 
123
    HTTP_MOVED_TEMPORARILY            = 302
 
124
    HTTP_SEE_OTHER                    = 303
 
125
    HTTP_NOT_MODIFIED                 = 304
 
126
    HTTP_USE_PROXY                    = 305
 
127
    HTTP_TEMPORARY_REDIRECT           = 307
 
128
    HTTP_BAD_REQUEST                  = 400
 
129
    HTTP_UNAUTHORIZED                 = 401
 
130
    HTTP_PAYMENT_REQUIRED             = 402
 
131
    HTTP_FORBIDDEN                    = 403
 
132
    HTTP_NOT_FOUND                    = 404
 
133
    HTTP_METHOD_NOT_ALLOWED           = 405
 
134
    HTTP_NOT_ACCEPTABLE               = 406
 
135
    HTTP_PROXY_AUTHENTICATION_REQUIRED= 407
 
136
    HTTP_REQUEST_TIME_OUT             = 408
 
137
    HTTP_CONFLICT                     = 409
 
138
    HTTP_GONE                         = 410
 
139
    HTTP_LENGTH_REQUIRED              = 411
 
140
    HTTP_PRECONDITION_FAILED          = 412
 
141
    HTTP_REQUEST_ENTITY_TOO_LARGE     = 413
 
142
    HTTP_REQUEST_URI_TOO_LARGE        = 414
 
143
    HTTP_UNSUPPORTED_MEDIA_TYPE       = 415
 
144
    HTTP_RANGE_NOT_SATISFIABLE        = 416
 
145
    HTTP_EXPECTATION_FAILED           = 417
 
146
    HTTP_UNPROCESSABLE_ENTITY         = 422
 
147
    HTTP_LOCKED                       = 423
 
148
    HTTP_FAILED_DEPENDENCY            = 424
 
149
    HTTP_INTERNAL_SERVER_ERROR        = 500
 
150
    HTTP_NOT_IMPLEMENTED              = 501
 
151
    HTTP_BAD_GATEWAY                  = 502
 
152
    HTTP_SERVICE_UNAVAILABLE          = 503
 
153
    HTTP_GATEWAY_TIME_OUT             = 504
 
154
    HTTP_VERSION_NOT_SUPPORTED        = 505
 
155
    HTTP_VARIANT_ALSO_VARIES          = 506
 
156
    HTTP_INSUFFICIENT_STORAGE         = 507
 
157
    HTTP_NOT_EXTENDED                 = 510
 
158
 
 
159
    def __init__(self, req, write_html_head):
 
160
        """Builds an IVLE request object from a mod_python request object.
 
161
        This results in an object with all of the necessary methods and
 
162
        additional fields.
 
163
 
 
164
        req: A mod_python request object.
 
165
        write_html_head: Function which is called when writing the automatic
 
166
            HTML header. Accepts a single argument, the IVLE request object.
 
167
        """
 
168
 
 
169
        # Methods are mostly wrappers around the Apache request object
 
170
        self.apache_req = req
 
171
        self.func_write_html_head = write_html_head
 
172
        self.headers_written = False
 
173
 
 
174
        # Determine if the browser used the public host name to make the
 
175
        # request (in which case we are in "public mode")
 
176
        if req.hostname == conf.public_host:
 
177
            self.publicmode = True
 
178
        else:
 
179
            self.publicmode = False
 
180
 
 
181
        # Inherit values for the input members
 
182
        self.method = req.method
 
183
        self.uri = req.uri
 
184
        # Split the given path into the app (top-level dir) and sub-path
 
185
        # (after first stripping away the root directory)
 
186
        path = common.util.unmake_path(req.uri)
 
187
        if self.publicmode:
 
188
            self.app = None
 
189
            (_, self.path) = (common.util.split_path(path))
 
190
        else:
 
191
            (self.app, self.path) = (common.util.split_path(path))
 
192
        self.user = None
 
193
        self.hostname = req.hostname
 
194
        self.headers_in = req.headers_in
 
195
        self.headers_out = req.headers_out
 
196
 
 
197
        # Default values for the output members
 
198
        self.status = Request.HTTP_OK
 
199
        self.content_type = None        # Use Apache's default
 
200
        self.location = None
 
201
        self.title = None     # Will be set by dispatch before passing to app
 
202
        self.styles = []
 
203
        self.scripts = []
 
204
        self.scripts_init = []
 
205
        self.write_html_head_foot = False
 
206
        self.got_common_vars = False
 
207
 
 
208
    def __writeheaders(self):
 
209
        """Writes out the HTTP and HTML headers before any real data is
 
210
        written."""
 
211
        self.headers_written = True
 
212
        # Prepare the HTTP and HTML headers before the first write is made
 
213
        if self.content_type != None:
 
214
            self.apache_req.content_type = self.content_type
 
215
        self.apache_req.status = self.status
 
216
        if self.location != None:
 
217
            self.apache_req.headers_out['Location'] = self.location
 
218
        if self.write_html_head_foot:
 
219
            # Write the HTML header, pass "self" (request object)
 
220
            self.func_write_html_head(self)
 
221
 
 
222
    def ensure_headers_written(self):
 
223
        """Writes out the HTTP and HTML headers if they haven't already been
 
224
        written."""
 
225
        if not self.headers_written:
 
226
            self.__writeheaders()
 
227
 
 
228
    def write(self, string, flush=1):
 
229
        """Writes string directly to the client, then flushes the buffer,
 
230
        unless flush is 0."""
 
231
 
 
232
        if not self.headers_written:
 
233
            self.__writeheaders()
 
234
        if isinstance(string, unicode):
 
235
            # Encode unicode strings as UTF-8
 
236
            # (Otherwise cannot handle being written to a bytestream)
 
237
            self.apache_req.write(string.encode('utf8'), flush)
 
238
        else:
 
239
            # 8-bit clean strings just get written directly.
 
240
            # This includes binary strings.
 
241
            self.apache_req.write(string, flush)
 
242
 
 
243
    def flush(self):
 
244
        """Flushes the output buffer."""
 
245
        self.apache_req.flush()
 
246
 
 
247
    def sendfile(self, filename):
 
248
        """Sends the named file directly to the client."""
 
249
        if not self.headers_written:
 
250
            self.__writeheaders()
 
251
        self.apache_req.sendfile(filename)
 
252
 
 
253
    def read(self, len=None):
 
254
        """Reads at most len bytes directly from the client. (See mod_python
 
255
        Request.read)."""
 
256
        if len is None:
 
257
            return self.apache_req.read()
 
258
        else:
 
259
            return self.apache_req.read(len)
 
260
 
 
261
    def throw_error(self, httpcode, message=None):
 
262
        """Writes out an HTTP error of the specified code. Raises an exception
 
263
        which is caught by the dispatch or web server, so any code following
 
264
        this call will not be executed.
 
265
 
 
266
        httpcode: An HTTP response status code. Pass a constant from the
 
267
        Request class.
 
268
        """
 
269
        raise common.util.IVLEError(httpcode, message)
 
270
 
 
271
    def throw_redirect(self, location):
 
272
        """Writes out an HTTP redirect to the specified URL. Raises an
 
273
        exception which is caught by the dispatch or web server, so any
 
274
        code following this call will not be executed.
 
275
 
 
276
        httpcode: An HTTP response status code. Pass a constant from the
 
277
        Request class.
 
278
        """
 
279
        mod_python.util.redirect(self.apache_req, location)
 
280
 
 
281
    def add_cookie(self, cookie, value=None, **attributes):
 
282
        """Inserts a cookie into this request object's headers."""
 
283
        if value is None:
 
284
            Cookie.add_cookie(self.apache_req, cookie)
 
285
        else:
 
286
            Cookie.add_cookie(self.apache_req, cookie, value, **attributes)
 
287
 
 
288
    def get_session(self):
 
289
        """Returns a mod_python Session object for this request.
 
290
        Note that this is dependent on mod_python and may need to change
 
291
        interface if porting away from mod_python."""
 
292
        # Cache the session object and set the timeout to 24 hours.
 
293
        if not hasattr(self, 'session'):
 
294
            self.session = Session.FileSession(self.apache_req,
 
295
                                               timeout = 60 * 60 * 24)
 
296
        return self.session
 
297
 
 
298
    def get_fieldstorage(self):
 
299
        """Returns a mod_python FieldStorage object for this request.
 
300
        Note that this is dependent on mod_python and may need to change
 
301
        interface if porting away from mod_python."""
 
302
        # Cache the fieldstorage object
 
303
        if not hasattr(self, 'fields'):
 
304
            self.fields = util.FieldStorage(self.apache_req)
 
305
        return self.fields
 
306
 
 
307
    def get_cgi_environ(self):
 
308
        """Returns the CGI environment emulation for this request. (Calls
 
309
        add_common_vars). The environment is returned as a mapping
 
310
        compatible with os.environ."""
 
311
        if not self.got_common_vars:
 
312
            self.apache_req.add_common_vars()
 
313
            self.got_common_vars = True
 
314
        return self.apache_req.subprocess_env
 
315
 
 
316
    @staticmethod
 
317
    def get_http_codename(code):
 
318
        """Given a HTTP error code int, returns a (name, description)
 
319
        pair, suitable for displaying to the user.
 
320
        May return (None,None) if code is unknown.
 
321
        Only lists common 4xx and 5xx codes (since this is just used
 
322
        to display throw_error error messages).
 
323
        """
 
324
        try:
 
325
            return http_codenames[code]
 
326
        except KeyError:
 
327
            return None, None
 
328
 
 
329
# Human strings for HTTP response codes
 
330
http_codenames = {
 
331
    Request.HTTP_BAD_REQUEST:
 
332
        ("Bad Request",
 
333
        "Your browser sent a request IVLE did not understand."),
 
334
    Request.HTTP_UNAUTHORIZED:
 
335
        ("Unauthorized",
 
336
        "You are not allowed to view this part of IVLE."),
 
337
    Request.HTTP_FORBIDDEN:
 
338
        ("Forbidden",
 
339
        "You are not allowed to view this part of IVLE."),
 
340
    Request.HTTP_NOT_FOUND:
 
341
        ("Not Found",
 
342
        "The application or file you requested does not exist."),
 
343
    Request.HTTP_METHOD_NOT_ALLOWED:
 
344
        ("Method Not Allowed",
 
345
        "Your browser is interacting with IVLE in the wrong way."
 
346
        "This is probably a bug in IVLE. "
 
347
        "Please report it to the administrators."),
 
348
    Request.HTTP_INTERNAL_SERVER_ERROR:
 
349
        ("Internal Server Error",
 
350
        "An unknown error occured in IVLE."),
 
351
    Request.HTTP_NOT_IMPLEMENTED:
 
352
        ("Not Implemented",
 
353
        "The application or file you requested has not been implemented "
 
354
        "in IVLE."),
 
355
    Request.HTTP_SERVICE_UNAVAILABLE:
 
356
        ("Service Unavailable",
 
357
        "IVLE is currently experiencing technical difficulties. "
 
358
        "Please try again later."),
 
359
}