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

1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
1
# IVLE - Informatics Virtual Learning Environment
1080.1.2 by matt.giuca
New module: ivle.database. Classes and utilities for Storm ORM.
2
# Copyright (C) 2007-2009 The University of Melbourne
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
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
1080.1.2 by matt.giuca
New module: ivle.database. Classes and utilities for Storm ORM.
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
"""
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
27
1099.1.5 by William Grant
ivle.dispatch{,.{login,request}}: Fix mod_python imports to ensure that we can
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
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
35
1208 by William Grant
Replace ivle.util.unmake_path with specialisations in Request and CGIRequest.
36
import os.path
37
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
38
import ivle.util
1080.1.2 by matt.giuca
New module: ivle.database. Classes and utilities for Storm ORM.
39
import ivle.database
1099.1.80 by William Grant
Port the forum app to the new framework. With it also comes new cookie
40
from ivle.webapp.base.plugins import CookiePlugin
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
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.
1080.1.2 by matt.giuca
New module: ivle.database. Classes and utilities for Storm ORM.
60
        store (read)
61
            storm.store.Store instance. Holds a database transaction open,
62
            which is available for the entire lifetime of the request.
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
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
1199 by William Grant
Populate req.config in a cleaner manner.
158
    def __init__(self, req, config):
159
        """Create an IVLE request from a mod_python one.
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
160
1199 by William Grant
Populate req.config in a cleaner manner.
161
        @param req: A mod_python request.
162
        @param config: An IVLE configuration.
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
163
        """
164
165
        # Methods are mostly wrappers around the Apache request object
166
        self.apache_req = req
1199 by William Grant
Populate req.config in a cleaner manner.
167
        self.config = config
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
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")
1199 by William Grant
Populate req.config in a cleaner manner.
172
        if req.hostname == config['urls']['public_host']:
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
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)
1208 by William Grant
Replace ivle.util.unmake_path with specialisations in Request and CGIRequest.
182
        path = self.unmake_path(req.uri)
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
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
1080.1.2 by matt.giuca
New module: ivle.database. Classes and utilities for Storm ORM.
189
        # Open a database connection and transaction, keep it around for users
190
        # of the Request object to use
1201 by William Grant
ivle.database.get_store() now takes a configuration object.
191
        self.store = ivle.database.get_store(config)
1080.1.2 by matt.giuca
New module: ivle.database. Classes and utilities for Storm ORM.
192
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
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
1080.1.2 by matt.giuca
New module: ivle.database. Classes and utilities for Storm ORM.
205
    def __del__(self):
206
        """Cleanup."""
207
        self.store.close()
208
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
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
1081 by me at id
ivle.conf, ivle.dispatch: Redo some of Nick's changes made between the
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
1099.1.5 by William Grant
ivle.dispatch{,.{login,request}}: Fix mod_python imports to ensure that we can
249
            all_cookies = mod_python.Cookie.get_cookies(self)
1099.1.80 by William Grant
Port the forum app to the new framework. With it also comes new cookie
250
251
            # Create cookies for plugins that might request them.
1092.1.61 by William Grant
Fix cookie deletion.
252
            for plugin in self.config.plugin_index[CookiePlugin]:
1099.1.80 by William Grant
Port the forum app to the new framework. With it also comes new cookie
253
                for cookie in plugin.cookies:
254
                    self.add_cookie(mod_python.Cookie.Cookie(cookie, '',
255
                                                    expires=1, path='/'))
1210 by William Grant
Use Request.make_path everywhere.
256
        self.throw_redirect(self.make_path(''))
1081 by me at id
ivle.conf, ivle.dispatch: Redo some of Nick's changes made between the
257
258
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
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
        """
1080.1.7 by matt.giuca
The new ivle.database.User class is now used in Request and usrmgt, which
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"))
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
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:
1099.1.5 by William Grant
ivle.dispatch{,.{login,request}}: Fix mod_python imports to ensure that we can
292
            mod_python.Cookie.add_cookie(self.apache_req, cookie)
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
293
        else:
1099.1.5 by William Grant
ivle.dispatch{,.{login,request}}: Fix mod_python imports to ensure that we can
294
            mod_python.Cookie.add_cookie(self.apache_req, cookie, value, **attributes)
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
295
1209 by William Grant
Add Request.make_path, to replace ivle.util.make_path.
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
1208 by William Grant
Replace ivle.util.unmake_path with specialisations in Request and CGIRequest.
305
    def unmake_path(self, path):
306
        """Strip the IVLE URL prefix from the given path, if present.
307
308
        Also normalises the path.
1209 by William Grant
Add Request.make_path, to replace ivle.util.make_path.
309
310
        This method is DEPRECATED. We no longer support use of a prefix.
1208 by William Grant
Replace ivle.util.unmake_path with specialisations in Request and CGIRequest.
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
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
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
1130 by William Grant
Unlock the session everywhere as soon as we are done with it, and add a warning
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
        """
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
331
        # Cache the session object and set the timeout to 24 hours.
332
        if not hasattr(self, 'session'):
1099.1.5 by William Grant
ivle.dispatch{,.{login,request}}: Fix mod_python imports to ensure that we can
333
            self.session = mod_python.Session.FileSession(self.apache_req,
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
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'):
1099.1.5 by William Grant
ivle.dispatch{,.{login,request}}: Fix mod_python imports to ensure that we can
343
            self.fields = mod_python.util.FieldStorage(self.apache_req)
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
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
}