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

« back to all changes in this revision

Viewing changes to www/dispatch/__init__.py

  • Committer: mattgiuca
  • Date: 2008-01-09 21:33:56 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:144
Trunk, and all subdirectories with Python files:
    Added to svn:ignore all *.pyc *.pyo, to avoid compiled files
    showing up in svn st / diff / commit lists.
    Added to svn:ignore trampoline/trampoline.

Show diffs side-by-side

added added

removed removed

Lines of Context:
27
27
# Then passes the request along to the appropriate ivle app.
28
28
 
29
29
import mod_python
30
 
from mod_python import apache, Cookie
 
30
from mod_python import apache
31
31
 
32
 
import sys
33
32
import os
34
33
import os.path
35
 
import urllib
36
 
 
37
34
import conf
38
35
import conf.apps
39
 
import conf.conf
40
36
import apps
41
37
 
42
38
from request import Request
43
39
import html
44
 
import cgi
45
40
import login
46
 
from common import (util, forumutil)
47
 
import traceback
48
 
import plugins.console
49
 
import logging
50
 
import socket
51
 
import time
52
 
 
53
 
# List of cookies that IVLE uses (to be removed at logout)
54
 
ivle_cookies = ["ivleforumcookie", "clipboard"]
 
41
from common import util
55
42
 
56
43
def handler(req):
57
44
    """Handles a request which may be to anywhere in the site except media.
61
48
    """
62
49
    # Make the request object into an IVLE request which can be passed to apps
63
50
    apachereq = req
64
 
    try:
65
 
        req = Request(req, html.write_html_head)
66
 
    except Exception:
67
 
        # Pass the apachereq to error reporter, since ivle req isn't created
68
 
        # yet.
69
 
        handle_unknown_exception(apachereq, *sys.exc_info())
70
 
        # Tell Apache not to generate its own errors as well
71
 
        return apache.OK
72
 
 
73
 
    # Run the main handler, and catch all exceptions
74
 
    try:
75
 
        return handler_(req, apachereq)
76
 
    except mod_python.apache.SERVER_RETURN:
77
 
        # An apache error. We discourage these, but they might still happen.
78
 
        # Just raise up.
79
 
        raise
80
 
    except Exception:
81
 
        handle_unknown_exception(req, *sys.exc_info())
82
 
        # Tell Apache not to generate its own errors as well
83
 
        return apache.OK
84
 
 
85
 
def handler_(req, apachereq):
86
 
    """
87
 
    Nested handler function. May raise exceptions. The top-level handler is
88
 
    just used to catch exceptions.
89
 
    Takes both an IVLE request and an Apache req.
90
 
    """
91
 
    # Hack? Try and get the user login early just in case we throw an error
92
 
    # (most likely 404) to stop us seeing not logged in even when we are.
93
 
    if not req.publicmode:
94
 
        req.user = login.get_user_details(req)
 
51
    req = Request(req, html.write_html_head)
95
52
 
96
53
    # Check req.app to see if it is valid. 404 if not.
97
54
    if req.app is not None and req.app not in conf.apps.app_url:
99
56
        if req.app == 'logout':
100
57
            logout(req)
101
58
        else:
102
 
            req.throw_error(Request.HTTP_NOT_FOUND,
103
 
                "There is no application called %s." % repr(req.app))
104
 
 
105
 
    # Special handling for public mode - only allow the public app, call it
106
 
    # and get out.
107
 
    # NOTE: This will not behave correctly if the public app uses
108
 
    # write_html_head_foot, but "serve" does not.
109
 
    if req.publicmode:
110
 
        if req.app != conf.apps.public_app:
111
 
            req.throw_error(Request.HTTP_FORBIDDEN,
112
 
                "This application is not available on the public site.")
113
 
        app = conf.apps.app_url[conf.apps.public_app]
114
 
        apps.call_app(app.dir, req)
115
 
        return req.OK
 
59
            # TODO: Nicer 404 message?
 
60
            req.throw_error(Request.HTTP_NOT_FOUND)
116
61
 
117
62
    # app is the App object for the chosen app
118
63
    if req.app is None:
119
 
        app = conf.apps.app_url[conf.apps.default_app]
 
64
        app = conf.apps.app_url[conf.default_app]
120
65
    else:
121
66
        app = conf.apps.app_url[req.app]
122
67
 
123
68
    # Check if app requires auth. If so, perform authentication and login.
124
 
    # This will either return a User object, None, or perform a redirect
125
 
    # which we will not catch here.
126
69
    if app.requireauth:
127
 
        req.user = login.login(req)
128
 
        logged_in = req.user is not None
 
70
        req.username = login.login(req)
 
71
        logged_in = req.username is not None
129
72
    else:
130
 
        req.user = login.get_user_details(req)
 
73
        req.username = login.get_username(req)
131
74
        logged_in = True
132
75
 
133
76
    if logged_in:
134
 
        # Keep the user's session alive by writing to the session object.
135
 
        # req.get_session().save()
136
 
        # Well, it's a fine idea, but it creates considerable grief in the
137
 
        # concurrent update department, so instead, we'll just make the
138
 
        # sessions not time out.
139
 
        req.get_session().unlock()
140
 
 
141
77
        # If user did not specify an app, HTTP redirect to default app and
142
78
        # exit.
143
79
        if req.app is None:
144
 
            req.throw_redirect(util.make_path(conf.apps.default_app))
 
80
            req.throw_redirect(util.make_path(conf.default_app))
145
81
 
146
82
        # Set the default title to the app's tab name, if any. Otherwise URL
147
83
        # name.
152
88
 
153
89
        # Call the specified app with the request object
154
90
        apps.call_app(app.dir, req)
155
 
 
156
91
    # if not logged in, login.login will have written the login box.
157
92
    # Just clean up and exit.
158
93
 
163
98
 
164
99
    # When done, write out the HTML footer if the app has requested it
165
100
    if req.write_html_head_foot:
166
 
        # Show the console if required
167
 
        if logged_in and app.useconsole:
168
 
            plugins.console.present(req, windowpane=True)
169
101
        html.write_html_foot(req)
170
102
 
171
103
    # Note: Apache will not write custom HTML error messages here.
178
110
    session = req.get_session()
179
111
    session.invalidate()
180
112
    session.delete()
181
 
    # Invalidates all IVLE cookies
182
 
    all_cookies = Cookie.get_cookies(req)
183
 
    for cookie in all_cookies:
184
 
        if cookie in ivle_cookies:
185
 
            req.add_cookie(Cookie.Cookie(cookie,'',expires=1,path='/'))
186
 
    req.throw_redirect(util.make_path('')) 
187
 
 
188
 
def handle_unknown_exception(req, exc_type, exc_value, exc_traceback):
189
 
    """
190
 
    Given an exception that has just been thrown from IVLE, print its details
191
 
    to the request.
192
 
    This is a full handler. It assumes nothing has been written, and writes a
193
 
    complete HTML page.
194
 
    req: May be EITHER an IVLE req or an Apache req.
195
 
    IVLE reqs may have the HTML head/foot written (on a 400 error), but
196
 
    the handler code may pass an apache req if an exception occurs before
197
 
    the IVLE request is created.
198
 
    """
199
 
    req.content_type = "text/html"
200
 
    logfile = os.path.join(conf.conf.log_path, 'ivle_error.log')
201
 
    logfail = False
202
 
    # For some reason, some versions of mod_python have "_server" instead of
203
 
    # "main_server". So we check for both.
204
 
    try:
205
 
        admin_email = apache.main_server.server_admin
206
 
    except AttributeError:
207
 
        try:
208
 
            admin_email = apache._server.server_admin
209
 
        except AttributeError:
210
 
            admin_email = ""
211
 
    try:
212
 
        httpcode = exc_value.httpcode
213
 
        req.status = httpcode
214
 
    except AttributeError:
215
 
        httpcode = None
216
 
        req.status = apache.HTTP_INTERNAL_SERVER_ERROR
217
 
    try:
218
 
        login = req.user.login
219
 
    except AttributeError:
220
 
        login = None
221
 
 
222
 
    # Log File
223
 
    try:
224
 
        for h in logging.getLogger().handlers:
225
 
            logging.getLogger().removeHandler(h)
226
 
        logging.basicConfig(level=logging.INFO,
227
 
            format='%(asctime)s %(levelname)s: ' +
228
 
                '(HTTP: ' + str(req.status) +
229
 
                ', Ref: ' + str(login) + '@' +
230
 
                str(socket.gethostname()) + str(req.uri) +
231
 
                ') %(message)s',
232
 
            filename=logfile,
233
 
            filemode='a')
234
 
    except IOError:
235
 
        logfail = True
236
 
    logging.debug('Logging Unhandled Exception')
237
 
 
238
 
    # We handle 3 types of error.
239
 
    # IVLEErrors with 4xx response codes (client error).
240
 
    # IVLEErrors with 5xx response codes (handled server error).
241
 
    # Other exceptions (unhandled server error).
242
 
    # IVLEErrors should not have other response codes than 4xx or 5xx
243
 
    # (eg. throw_redirect should have been used for 3xx codes).
244
 
    # Therefore, that is treated as an unhandled error.
245
 
 
246
 
    if (exc_type == util.IVLEError and httpcode >= 400
247
 
        and httpcode <= 499):
248
 
        # IVLEErrors with 4xx response codes are client errors.
249
 
        # Therefore, these have a "nice" response (we even coat it in the IVLE
250
 
        # HTML wrappers).
251
 
        
252
 
        req.write_html_head_foot = True
253
 
        req.write_javascript_settings = False
254
 
        req.write('<div id="ivle_padding">\n')
255
 
        try:
256
 
            codename, msg = req.get_http_codename(httpcode)
257
 
        except AttributeError:
258
 
            codename, msg = None, None
259
 
        # Override the default message with the supplied one,
260
 
        # if available.
261
 
        if exc_value.message is not None:
262
 
            msg = exc_value.message
263
 
        if codename is not None:
264
 
            req.write("<h1>Error: %s</h1>\n" % cgi.escape(codename))
265
 
        else:
266
 
            req.write("<h1>Error</h1>\n")
267
 
        if msg is not None:
268
 
            req.write("<p>%s</p>\n" % cgi.escape(msg))
269
 
        else:
270
 
            req.write("<p>An unknown error occured.</p>\n")
271
 
        
272
 
        # Logging
273
 
        logging.info(str(msg))
274
 
        
275
 
        req.write("<p>(HTTP error code %d)</p>\n" % httpcode)
276
 
        if logfail:
277
 
            req.write("<p>Warning: Could not open Error Log: '%s'</p>\n"
278
 
                %cgi.escape(logfile))
279
 
        req.write('</div>\n')
280
 
        html.write_html_foot(req)
281
 
    else:
282
 
        # A "bad" error message. We shouldn't get here unless IVLE
283
 
        # misbehaves (which is currently very easy, if things aren't set up
284
 
        # correctly).
285
 
        # Write the traceback.
286
 
        # If this is a non-4xx IVLEError, get the message and httpcode and
287
 
        # make the error message a bit nicer (but still include the
288
 
        # traceback).
289
 
        # We also need to special-case IVLEJailError, as we can get another
290
 
        # almost-exception out of it.
291
 
 
292
 
        codename, msg = None, None
293
 
 
294
 
        if exc_type is util.IVLEJailError:
295
 
            msg = exc_value.type_str + ": " + exc_value.message
296
 
            tb = 'Exception information extracted from IVLEJailError:\n'
297
 
            tb += urllib.unquote(exc_value.info)
298
 
        else:
299
 
            try:
300
 
                codename, msg = req.get_http_codename(httpcode)
301
 
            except AttributeError:
302
 
                pass
303
 
            # Override the default message with the supplied one,
304
 
            # if available.
305
 
            if hasattr(exc_value, 'message') and exc_value.message is not None:
306
 
                msg = exc_value.message
307
 
                # Prepend the exception type
308
 
                if exc_type != util.IVLEError:
309
 
                    msg = exc_type.__name__ + ": " + msg
310
 
 
311
 
            tb = ''.join(traceback.format_exception(exc_type, exc_value,
312
 
                                                    exc_traceback))
313
 
 
314
 
        # Logging
315
 
        logging.error('%s\n%s'%(str(msg), tb))
316
 
 
317
 
        req.write("""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"                 
318
 
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">                                      
319
 
<html xmlns="http://www.w3.org/1999/xhtml">
320
 
<head><title>IVLE Internal Server Error</title></head>
321
 
<body>
322
 
<h1>IVLE Internal Server Error""")
323
 
        if (codename is not None
324
 
            and httpcode != apache.HTTP_INTERNAL_SERVER_ERROR):
325
 
            req.write(": %s" % cgi.escape(codename))
326
 
        req.write("""</h1>
327
 
<p>An error has occured which is the fault of the IVLE developers or
328
 
administration.</p>
329
 
""")
330
 
        if msg is not None:
331
 
            req.write("<p>%s</p>\n" % cgi.escape(msg))
332
 
        if httpcode is not None:
333
 
            req.write("<p>(HTTP error code %d)</p>\n" % httpcode)
334
 
        req.write("""
335
 
<p>Please report this to <a href="mailto:%s">%s</a> (the system
336
 
administrator). Include the following information:</p>
337
 
""" % (cgi.escape(admin_email), cgi.escape(admin_email)))
338
 
 
339
 
        req.write("<pre>\n%s\n</pre>\n"%cgi.escape(tb))
340
 
        if logfail:
341
 
            req.write("<p>Warning: Could not open Error Log: '%s'</p>\n"
342
 
                %cgi.escape(logfile))
343
 
        req.write("</body></html>")
 
113
    req.throw_redirect(util.make_path(''))