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

« back to all changes in this revision

Viewing changes to ivle/dispatch/request.py

  • Committer: dcoles
  • Date: 2008-02-29 02:11:58 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:624
forum: Removed the subsilver2 style and phpBB installer
Modified prosilver theme to be more IVLE integrated
Added db dumps for setup

setup.py: Added config.php generator code

doc/setup/install_proc.txt: New setup/install details

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# IVLE - Informatics Virtual Learning Environment
2
 
# Copyright (C) 2007-2009 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
 
# Author: Matt Giuca
19
 
 
20
 
"""
21
 
IVLE Request Object
22
 
 
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
25
 
object.
26
 
"""
27
 
 
28
 
try:
29
 
    import mod_python.Session
30
 
    import mod_python.Cookie
31
 
    import mod_python.util
32
 
except ImportError:
33
 
    # This needs to be importable from outside Apache.
34
 
    pass
35
 
 
36
 
import os.path
37
 
 
38
 
import ivle.util
39
 
import ivle.database
40
 
from ivle.webapp.base.plugins import CookiePlugin
41
 
 
42
 
class Request:
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.
45
 
 
46
 
    Request object attributes:
47
 
        method (read)
48
 
            String. The request method (eg. 'GET', 'POST', etc)
49
 
        uri (read)
50
 
            String. The path portion of the URI.
51
 
        app (read)
52
 
            String. Name of the application specified in the URL, or None.
53
 
        path (read)
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".
57
 
        user (read)
58
 
            User object. Details of the user who is currently logged in, or
59
 
            None.
60
 
        store (read)
61
 
            storm.store.Store instance. Holds a database transaction open,
62
 
            which is available for the entire lifetime of the request.
63
 
        hostname (read)
64
 
            String. Hostname the server is running on.
65
 
        headers_in (read)
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.
69
 
        publicmode (read)
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).
73
 
 
74
 
        status (write)
75
 
            Int. Response status number. Use one of the status codes defined
76
 
            in class Request.
77
 
        content_type (write)
78
 
            String. The Content-Type (mime type) header value.
79
 
        location (write)
80
 
            String. Response "Location" header value. Used with HTTP redirect
81
 
            responses.
82
 
        styles (write)
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
87
 
            to be site-relative.
88
 
        scripts (write)
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
93
 
            to be site-relative.
94
 
        scripts_init (write)
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 
99
 
            page load time.
100
 
    """
101
 
 
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.
105
 
    OK  = 0
106
 
 
107
 
    # HTTP status codes
108
 
 
109
 
    HTTP_CONTINUE                     = 100
110
 
    HTTP_SWITCHING_PROTOCOLS          = 101
111
 
    HTTP_PROCESSING                   = 102
112
 
    HTTP_OK                           = 200
113
 
    HTTP_CREATED                      = 201
114
 
    HTTP_ACCEPTED                     = 202
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
123
 
    HTTP_SEE_OTHER                    = 303
124
 
    HTTP_NOT_MODIFIED                 = 304
125
 
    HTTP_USE_PROXY                    = 305
126
 
    HTTP_TEMPORARY_REDIRECT           = 307
127
 
    HTTP_BAD_REQUEST                  = 400
128
 
    HTTP_UNAUTHORIZED                 = 401
129
 
    HTTP_PAYMENT_REQUIRED             = 402
130
 
    HTTP_FORBIDDEN                    = 403
131
 
    HTTP_NOT_FOUND                    = 404
132
 
    HTTP_METHOD_NOT_ALLOWED           = 405
133
 
    HTTP_NOT_ACCEPTABLE               = 406
134
 
    HTTP_PROXY_AUTHENTICATION_REQUIRED= 407
135
 
    HTTP_REQUEST_TIME_OUT             = 408
136
 
    HTTP_CONFLICT                     = 409
137
 
    HTTP_GONE                         = 410
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
146
 
    HTTP_LOCKED                       = 423
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
157
 
 
158
 
    def __init__(self, req, config):
159
 
        """Create an IVLE request from a mod_python one.
160
 
 
161
 
        @param req: A mod_python request.
162
 
        @param config: An IVLE configuration.
163
 
        """
164
 
 
165
 
        # Methods are mostly wrappers around the Apache request object
166
 
        self.apache_req = req
167
 
        self.config = config
168
 
        self.headers_written = False
169
 
 
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
174
 
        else:
175
 
            self.publicmode = False
176
 
 
177
 
        # Inherit values for the input members
178
 
        self.method = req.method
179
 
        self.uri = req.uri
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))
184
 
        self.user = None
185
 
        self.hostname = req.hostname
186
 
        self.headers_in = req.headers_in
187
 
        self.headers_out = req.headers_out
188
 
 
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)
192
 
 
193
 
        # Default values for the output members
194
 
        self.status = Request.HTTP_OK
195
 
        self.content_type = None        # Use Apache's default
196
 
        self.location = None
197
 
        self.styles = []
198
 
        self.scripts = []
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
204
 
 
205
 
    def __del__(self):
206
 
        """Cleanup."""
207
 
        self.store.close()
208
 
 
209
 
    def __writeheaders(self):
210
 
        """Writes out the HTTP and HTML headers before any real data is
211
 
        written."""
212
 
        self.headers_written = True
213
 
 
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
220
 
 
221
 
    def ensure_headers_written(self):
222
 
        """Writes out the HTTP and HTML headers if they haven't already been
223
 
        written."""
224
 
        if not self.headers_written:
225
 
            self.__writeheaders()
226
 
 
227
 
    def write(self, string, flush=1):
228
 
        """Writes string directly to the client, then flushes the buffer,
229
 
        unless flush is 0."""
230
 
 
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)
237
 
        else:
238
 
            # 8-bit clean strings just get written directly.
239
 
            # This includes binary strings.
240
 
            self.apache_req.write(string, flush)
241
 
 
242
 
    def logout(self):
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)
250
 
 
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(''))
257
 
 
258
 
 
259
 
    def flush(self):
260
 
        """Flushes the output buffer."""
261
 
        self.apache_req.flush()
262
 
 
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)
268
 
 
269
 
    def read(self, len=None):
270
 
        """Reads at most len bytes directly from the client. (See mod_python
271
 
        Request.read)."""
272
 
        if len is None:
273
 
            return self.apache_req.read()
274
 
        else:
275
 
            return self.apache_req.read(len)
276
 
 
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.
281
 
 
282
 
        httpcode: An HTTP response status code. Pass a constant from the
283
 
        Request class.
284
 
        """
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"))
288
 
 
289
 
    def add_cookie(self, cookie, value=None, **attributes):
290
 
        """Inserts a cookie into this request object's headers."""
291
 
        if value is None:
292
 
            mod_python.Cookie.add_cookie(self.apache_req, cookie)
293
 
        else:
294
 
            mod_python.Cookie.add_cookie(self.apache_req, cookie, value, **attributes)
295
 
 
296
 
    def make_path(self, path):
297
 
        """Prepend the IVLE URL prefix to the given path.
298
 
 
299
 
        This is used when generating URLs to send to the client.
300
 
 
301
 
        This method is DEPRECATED. We no longer support use of a prefix.
302
 
        """
303
 
        return os.path.join(self.config['urls']['root'], path)
304
 
 
305
 
    def unmake_path(self, path):
306
 
        """Strip the IVLE URL prefix from the given path, if present.
307
 
 
308
 
        Also normalises the path.
309
 
 
310
 
        This method is DEPRECATED. We no longer support use of a prefix.
311
 
        """
312
 
        path = os.path.normpath(path)
313
 
        root = os.path.normpath(self.config['urls']['root'])
314
 
 
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:
319
 
                path = path[1:]
320
 
 
321
 
        return path
322
 
 
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.
327
 
 
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!
330
 
        """
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)
335
 
        return self.session
336
 
 
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)
344
 
        return self.fields
345
 
 
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
354
 
 
355
 
    @staticmethod
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).
362
 
        """
363
 
        try:
364
 
            return http_codenames[code]
365
 
        except KeyError:
366
 
            return None, None
367
 
 
368
 
# Human strings for HTTP response codes
369
 
http_codenames = {
370
 
    Request.HTTP_BAD_REQUEST:
371
 
        ("Bad Request",
372
 
        "Your browser sent a request IVLE did not understand."),
373
 
    Request.HTTP_UNAUTHORIZED:
374
 
        ("Unauthorized",
375
 
        "You are not allowed to view this part of IVLE."),
376
 
    Request.HTTP_FORBIDDEN:
377
 
        ("Forbidden",
378
 
        "You are not allowed to view this part of IVLE."),
379
 
    Request.HTTP_NOT_FOUND:
380
 
        ("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:
391
 
        ("Not Implemented",
392
 
        "The application or file you requested has not been implemented "
393
 
        "in IVLE."),
394
 
    Request.HTTP_SERVICE_UNAVAILABLE:
395
 
        ("Service Unavailable",
396
 
        "IVLE is currently experiencing technical difficulties. "
397
 
        "Please try again later."),
398
 
}