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

« back to all changes in this revision

Viewing changes to www/dispatch/__init__.py

  • Committer: me at id
  • Date: 2009-01-14 22:42:10 UTC
  • mto: This revision was merged to the branch mainline in revision 1090.
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:branches%2Fstorm:1133
install_proc.txt: Add dependencies on python-{storm,psycopg2}.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# IVLE
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
19
 
# Author: Matt Giuca
20
 
# Date: 11/12/2007
21
 
 
22
 
# This is a mod_python handler program. The correct way to call it is to have
23
 
# Apache send all requests to be handled by the module 'dispatch'.
24
 
 
25
 
# Top-level handler. Handles all requests to all pages in IVLE.
26
 
# Handles authentication (not authorization).
27
 
# Then passes the request along to the appropriate ivle app.
28
 
 
29
 
import mod_python
30
 
from mod_python import apache
31
 
 
32
 
import sys
33
 
import os
34
 
import os.path
35
 
import conf
36
 
import conf.apps
37
 
import apps
38
 
 
39
 
from request import Request
40
 
import html
41
 
import cgi
42
 
import login
43
 
from common import (util, forumutil)
44
 
import traceback
45
 
import cStringIO
46
 
 
47
 
def handler(req):
48
 
    """Handles a request which may be to anywhere in the site except media.
49
 
    Intended to be called by mod_python, as a handler.
50
 
 
51
 
    req: An Apache request object.
52
 
    """
53
 
    # Make the request object into an IVLE request which can be passed to apps
54
 
    apachereq = req
55
 
    try:
56
 
        req = Request(req, html.write_html_head)
57
 
    except Exception:
58
 
        # Pass the apachereq to error reporter, since ivle req isn't created
59
 
        # yet.
60
 
        handle_unknown_exception(apachereq, *sys.exc_info())
61
 
        # Tell Apache not to generate its own errors as well
62
 
        return apache.OK
63
 
 
64
 
    # Run the main handler, and catch all exceptions
65
 
    try:
66
 
        return handler_(req, apachereq)
67
 
    except mod_python.apache.SERVER_RETURN:
68
 
        # An apache error. We discourage these, but they might still happen.
69
 
        # Just raise up.
70
 
        raise
71
 
    except Exception:
72
 
        handle_unknown_exception(req, *sys.exc_info())
73
 
        # Tell Apache not to generate its own errors as well
74
 
        return apache.OK
75
 
 
76
 
def handler_(req, apachereq):
77
 
    """
78
 
    Nested handler function. May raise exceptions. The top-level handler is
79
 
    just used to catch exceptions.
80
 
    Takes both an IVLE request and an Apache req.
81
 
    """
82
 
    # Check req.app to see if it is valid. 404 if not.
83
 
    if req.app is not None and req.app not in conf.apps.app_url:
84
 
        # Maybe it is a special app!
85
 
        if req.app == 'logout':
86
 
            logout(req)
87
 
        else:
88
 
            req.throw_error(Request.HTTP_NOT_FOUND,
89
 
                "There is no application called %s." % repr(req.app))
90
 
 
91
 
    # Special handling for public mode - just call public app and get out
92
 
    # NOTE: This will not behave correctly if the public app uses
93
 
    # write_html_head_foot, but "serve" does not.
94
 
    if req.publicmode:
95
 
        app = conf.apps.app_url[conf.apps.public_app]
96
 
        apps.call_app(app.dir, req)
97
 
        return req.OK
98
 
 
99
 
    # app is the App object for the chosen app
100
 
    if req.app is None:
101
 
        app = conf.apps.app_url[conf.apps.default_app]
102
 
    else:
103
 
        app = conf.apps.app_url[req.app]
104
 
 
105
 
    # Check if app requires auth. If so, perform authentication and login.
106
 
    # This will either return a User object, None, or perform a redirect
107
 
    # which we will not catch here.
108
 
    if app.requireauth:
109
 
        req.user = login.login(req)
110
 
        logged_in = req.user is not None
111
 
    else:
112
 
        req.user = login.get_user_details(req)
113
 
        logged_in = True
114
 
 
115
 
    if logged_in:
116
 
        # Keep the user's session alive by writing to the session object.
117
 
        # req.get_session().save()
118
 
        # Well, it's a fine idea, but it creates considerable grief in the
119
 
        # concurrent update department, so instead, we'll just make the
120
 
        # sessions not time out.
121
 
        
122
 
        # If user did not specify an app, HTTP redirect to default app and
123
 
        # exit.
124
 
        if req.app is None:
125
 
            req.throw_redirect(util.make_path(conf.apps.default_app))
126
 
 
127
 
        # Set the default title to the app's tab name, if any. Otherwise URL
128
 
        # name.
129
 
        if app.name is not None:
130
 
            req.title = app.name
131
 
        else:
132
 
            req.title = req.app
133
 
 
134
 
        # Call the specified app with the request object
135
 
        apps.call_app(app.dir, req)
136
 
 
137
 
    # if not logged in, login.login will have written the login box.
138
 
    # Just clean up and exit.
139
 
 
140
 
    # MAKE SURE we write the HTTP (and possibly HTML) header. This
141
 
    # wouldn't happen if nothing else ever got written, so we have to make
142
 
    # sure.
143
 
    req.ensure_headers_written()
144
 
 
145
 
    # When done, write out the HTML footer if the app has requested it
146
 
    if req.write_html_head_foot:
147
 
        html.write_html_foot(req)
148
 
 
149
 
    # Note: Apache will not write custom HTML error messages here.
150
 
    # Use req.throw_error to do that.
151
 
    return req.OK
152
 
 
153
 
def logout(req):
154
 
    """Log out the current user (if any) by destroying the session state.
155
 
    Then redirect to the top-level IVLE page."""
156
 
    session = req.get_session()
157
 
    session.invalidate()
158
 
    session.delete()
159
 
    req.add_cookie(forumutil.invalidated_forum_cookie())
160
 
    req.throw_redirect(util.make_path(''))
161
 
 
162
 
def handle_unknown_exception(req, exc_type, exc_value, exc_traceback):
163
 
    """
164
 
    Given an exception that has just been thrown from IVLE, print its details
165
 
    to the request.
166
 
    This is a full handler. It assumes nothing has been written, and writes a
167
 
    complete HTML page.
168
 
    req: May be EITHER an IVLE req or an Apache req.
169
 
    IVLE reqs may have the HTML head/foot written (on a 400 error), but
170
 
    the handler code may pass an apache req if an exception occurs before
171
 
    the IVLE request is created.
172
 
    """
173
 
    req.content_type = "text/html"
174
 
    # For some reason, some versions of mod_python have "_server" instead of
175
 
    # "main_server". So we check for both.
176
 
    try:
177
 
        admin_email = apache.main_server.server_admin
178
 
    except AttributeError:
179
 
        try:
180
 
            admin_email = apache._server.server_admin
181
 
        except AttributeError:
182
 
            admin_email = ""
183
 
    try:
184
 
        httpcode = exc_value.httpcode
185
 
        req.status = httpcode
186
 
    except AttributeError:
187
 
        httpcode = None
188
 
        req.status = apache.HTTP_INTERNAL_SERVER_ERROR
189
 
    # We handle 3 types of error.
190
 
    # IVLEErrors with 4xx response codes (client error).
191
 
    # IVLEErrors with 5xx response codes (handled server error).
192
 
    # Other exceptions (unhandled server error).
193
 
    # IVLEErrors should not have other response codes than 4xx or 5xx
194
 
    # (eg. throw_redirect should have been used for 3xx codes).
195
 
    # Therefore, that is treated as an unhandled error.
196
 
 
197
 
    if (exc_type == util.IVLEError and httpcode >= 400
198
 
        and httpcode <= 499):
199
 
        # IVLEErrors with 4xx response codes are client errors.
200
 
        # Therefore, these have a "nice" response (we even coat it in the IVLE
201
 
        # HTML wrappers).
202
 
        req.write_html_head_foot = True
203
 
        req.write('<div id="ivle_padding">\n')
204
 
        try:
205
 
            codename, msg = req.get_http_codename(httpcode)
206
 
        except AttributeError:
207
 
            codename, msg = None, None
208
 
        # Override the default message with the supplied one,
209
 
        # if available.
210
 
        if exc_value.message is not None:
211
 
            msg = exc_value.message
212
 
        if codename is not None:
213
 
            req.write("<h1>Error: %s</h1>\n" % cgi.escape(codename))
214
 
        else:
215
 
            req.write("<h1>Error</h1>\n")
216
 
        if msg is not None:
217
 
            req.write("<p>%s</p>\n" % cgi.escape(msg))
218
 
        else:
219
 
            req.write("<p>An unknown error occured.</p>\n")
220
 
        req.write("<p>(HTTP error code %d)</p>\n" % httpcode)
221
 
        req.write('</div>\n')
222
 
    else:
223
 
        # A "bad" error message. We shouldn't get here unless IVLE
224
 
        # misbehaves (which is currently very easy, if things aren't set up
225
 
        # correctly).
226
 
        # Write the traceback.
227
 
        # If this is a non-4xx IVLEError, get the message and httpcode and
228
 
        # make the error message a bit nicer (but still include the
229
 
        # traceback).
230
 
        try:
231
 
            codename, msg = req.get_http_codename(httpcode)
232
 
        except AttributeError:
233
 
            codename, msg = None, None
234
 
        # Override the default message with the supplied one,
235
 
        # if available.
236
 
        if hasattr(exc_value, 'message') and exc_value.message is not None:
237
 
            msg = exc_value.message
238
 
            # Prepend the exception type
239
 
            if exc_type != util.IVLEError:
240
 
                msg = exc_type.__name__ + ": " + msg
241
 
 
242
 
        req.write("""<html>
243
 
<head><title>IVLE Internal Server Error</title></head>
244
 
<body>
245
 
<h1>IVLE Internal Server Error""")
246
 
        if (codename is not None
247
 
            and httpcode != apache.HTTP_INTERNAL_SERVER_ERROR):
248
 
            req.write(": %s" % cgi.escape(codename))
249
 
        req.write("""</h1>
250
 
<p>An error has occured which is the fault of the IVLE developers or
251
 
administration.</p>
252
 
""")
253
 
        if msg is not None:
254
 
            req.write("<p>%s</p>\n" % cgi.escape(msg))
255
 
        if httpcode is not None:
256
 
            req.write("<p>(HTTP error code %d)</p>\n" % httpcode)
257
 
        req.write("""
258
 
<p>Please report this to <a href="mailto:%s">%s</a> (the system
259
 
administrator). Include the following information:</p>
260
 
""" % (cgi.escape(admin_email), cgi.escape(admin_email)))
261
 
 
262
 
        tb_print = cStringIO.StringIO()
263
 
        traceback.print_exception(exc_type, exc_value, exc_traceback,
264
 
            file=tb_print)
265
 
        req.write("<pre>\n")
266
 
        req.write(cgi.escape(tb_print.getvalue()))
267
 
        req.write("</pre>\n</body>\n")