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

93 by mattgiuca
New directory hierarchy.
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
975 by dcoles
Cookies: We now invalidate (expire and blank) all cookies at logout. Also fixed
30
from mod_python import apache, Cookie
93 by mattgiuca
New directory hierarchy.
31
540 by mattgiuca
Refactored error handling and reporting. Much friendlier error messages, for
32
import sys
93 by mattgiuca
New directory hierarchy.
33
import os
34
import os.path
853 by wagrant
dispatch: Extract exception information from IVLEJailErrors if caught.
35
import urllib
36
93 by mattgiuca
New directory hierarchy.
37
import conf
38
import conf.apps
893 by dcoles
Dispatch: Now attempts to log unhandled exceptions to a log directory specified
39
import conf.conf
93 by mattgiuca
New directory hierarchy.
40
import apps
41
42
from request import Request
43
import html
574 by mattgiuca
dispatch: Error reporting.
44
import cgi
124 by mattgiuca
dispatch/request: Added new fields: method and username.
45
import login
493 by dcoles
session.php: More interfaceing between IVLE and phpBB. Adds groups, emails and
46
from common import (util, forumutil)
540 by mattgiuca
Refactored error handling and reporting. Much friendlier error messages, for
47
import traceback
882 by dcoles
Console: To fix bug [ 2018542 ] 'Console shown regardless of login status'
48
import plugins.console
893 by dcoles
Dispatch: Now attempts to log unhandled exceptions to a log directory specified
49
import logging
50
import socket
975 by dcoles
Cookies: We now invalidate (expire and blank) all cookies at logout. Also fixed
51
import time
93 by mattgiuca
New directory hierarchy.
52
979 by dcoles
Logout: We now only remove cookies that are explicitly marked as IVLE cookies.
53
# List of cookies that IVLE uses (to be removed at logout)
54
ivle_cookies = ["ivleforumcookie", "clipboard"]
55
93 by mattgiuca
New directory hierarchy.
56
def handler(req):
57
    """Handles a request which may be to anywhere in the site except media.
58
    Intended to be called by mod_python, as a handler.
59
60
    req: An Apache request object.
61
    """
62
    # Make the request object into an IVLE request which can be passed to apps
63
    apachereq = req
540 by mattgiuca
Refactored error handling and reporting. Much friendlier error messages, for
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
    """
896 by dcoles
Dispatch: Try and get userid from session as early as possible. This is to
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.
932 by wagrant
dispatch (public): Don't attempt to get user details if we are on the
93
    if not req.publicmode:
94
        req.user = login.get_user_details(req)
896 by dcoles
Dispatch: Try and get userid from session as early as possible. This is to
95
93 by mattgiuca
New directory hierarchy.
96
    # Check req.app to see if it is valid. 404 if not.
97
    if req.app is not None and req.app not in conf.apps.app_url:
124 by mattgiuca
dispatch/request: Added new fields: method and username.
98
        # Maybe it is a special app!
99
        if req.app == 'logout':
100
            logout(req)
101
        else:
553 by mattgiuca
Added new app: Settings (UI for userservice).
102
            req.throw_error(Request.HTTP_NOT_FOUND,
103
                "There is no application called %s." % repr(req.app))
93 by mattgiuca
New directory hierarchy.
104
932 by wagrant
dispatch (public): Don't attempt to get user details if we are on the
105
    # Special handling for public mode - only allow the public app, call it
106
    # and get out.
259 by mattgiuca
setup.py: Added a new config variable "public_host", which lets the admin set
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:
932 by wagrant
dispatch (public): Don't attempt to get user details if we are on the
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.")
259 by mattgiuca
setup.py: Added a new config variable "public_host", which lets the admin set
113
        app = conf.apps.app_url[conf.apps.public_app]
114
        apps.call_app(app.dir, req)
115
        return req.OK
116
93 by mattgiuca
New directory hierarchy.
117
    # app is the App object for the chosen app
118
    if req.app is None:
195 by mattgiuca
Configuration: Moved "default_app" setting from conf/conf.py to conf/apps.py.
119
        app = conf.apps.app_url[conf.apps.default_app]
93 by mattgiuca
New directory hierarchy.
120
    else:
121
        app = conf.apps.app_url[req.app]
122
123
    # Check if app requires auth. If so, perform authentication and login.
504 by mattgiuca
Warning: Broken build, but rather unavoidable or this commit will spiral out
124
    # This will either return a User object, None, or perform a redirect
125
    # which we will not catch here.
93 by mattgiuca
New directory hierarchy.
126
    if app.requireauth:
504 by mattgiuca
Warning: Broken build, but rather unavoidable or this commit will spiral out
127
        req.user = login.login(req)
128
        logged_in = req.user is not None
93 by mattgiuca
New directory hierarchy.
129
    else:
504 by mattgiuca
Warning: Broken build, but rather unavoidable or this commit will spiral out
130
        req.user = login.get_user_details(req)
124 by mattgiuca
dispatch/request: Added new fields: method and username.
131
        logged_in = True
132
133
    if logged_in:
338 by mattgiuca
dispatch: Saves the session every time a request is made. This keeps the users
134
        # Keep the user's session alive by writing to the session object.
444 by drtomc
dispatch: Change the session timeout to 24 hours (there doesn't seem to be
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.
1019 by wagrant
dispatch: Unlock the session just before we launch the app. If we don't
139
        req.get_session().unlock()
140
124 by mattgiuca
dispatch/request: Added new fields: method and username.
141
        # If user did not specify an app, HTTP redirect to default app and
142
        # exit.
143
        if req.app is None:
195 by mattgiuca
Configuration: Moved "default_app" setting from conf/conf.py to conf/apps.py.
144
            req.throw_redirect(util.make_path(conf.apps.default_app))
124 by mattgiuca
dispatch/request: Added new fields: method and username.
145
146
        # Set the default title to the app's tab name, if any. Otherwise URL
147
        # name.
148
        if app.name is not None:
149
            req.title = app.name
150
        else:
151
            req.title = req.app
152
153
        # Call the specified app with the request object
154
        apps.call_app(app.dir, req)
540 by mattgiuca
Refactored error handling and reporting. Much friendlier error messages, for
155
124 by mattgiuca
dispatch/request: Added new fields: method and username.
156
    # if not logged in, login.login will have written the login box.
157
    # Just clean up and exit.
93 by mattgiuca
New directory hierarchy.
158
159
    # MAKE SURE we write the HTTP (and possibly HTML) header. This
160
    # wouldn't happen if nothing else ever got written, so we have to make
161
    # sure.
162
    req.ensure_headers_written()
163
164
    # When done, write out the HTML footer if the app has requested it
165
    if req.write_html_head_foot:
882 by dcoles
Console: To fix bug [ 2018542 ] 'Console shown regardless of login status'
166
        # Show the console if required
167
        if logged_in and app.useconsole:
168
            plugins.console.present(req, windowpane=True)
93 by mattgiuca
New directory hierarchy.
169
        html.write_html_foot(req)
170
124 by mattgiuca
dispatch/request: Added new fields: method and username.
171
    # Note: Apache will not write custom HTML error messages here.
172
    # Use req.throw_error to do that.
173
    return req.OK
93 by mattgiuca
New directory hierarchy.
174
124 by mattgiuca
dispatch/request: Added new fields: method and username.
175
def logout(req):
176
    """Log out the current user (if any) by destroying the session state.
177
    Then redirect to the top-level IVLE page."""
178
    session = req.get_session()
179
    session.invalidate()
180
    session.delete()
979 by dcoles
Logout: We now only remove cookies that are explicitly marked as IVLE cookies.
181
    # Invalidates all IVLE cookies
975 by dcoles
Cookies: We now invalidate (expire and blank) all cookies at logout. Also fixed
182
    all_cookies = Cookie.get_cookies(req)
183
    for cookie in all_cookies:
979 by dcoles
Logout: We now only remove cookies that are explicitly marked as IVLE cookies.
184
        if cookie in ivle_cookies:
185
            req.add_cookie(Cookie.Cookie(cookie,'',expires=1,path='/'))
975 by dcoles
Cookies: We now invalidate (expire and blank) all cookies at logout. Also fixed
186
    req.throw_redirect(util.make_path('')) 
540 by mattgiuca
Refactored error handling and reporting. Much friendlier error messages, for
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"
893 by dcoles
Dispatch: Now attempts to log unhandled exceptions to a log directory specified
200
    logfile = os.path.join(conf.conf.log_path, 'ivle_error.log')
201
    logfail = False
558 by mattgiuca
dispatch: Fixed error on some setups from trying to read admin email.
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 = ""
540 by mattgiuca
Refactored error handling and reporting. Much friendlier error messages, for
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
893 by dcoles
Dispatch: Now attempts to log unhandled exceptions to a log directory specified
217
    try:
218
        login = req.user.login
219
    except AttributeError:
220
        login = None
221
222
    # Log File
223
    try:
224
        logging.basicConfig(level=logging.INFO,
225
            format='%(asctime)s %(levelname)s: ' +
226
                '(HTTP: ' + str(req.status) +
227
                ', Ref: ' + str(login) + '@' +
228
                str(socket.gethostname()) + str(req.uri) +
229
                ') %(message)s',
230
            filename=logfile,
231
            filemode='a')
232
    except IOError:
233
        logfail = True
234
    logging.debug('Logging Unhandled Exception')
235
540 by mattgiuca
Refactored error handling and reporting. Much friendlier error messages, for
236
    # We handle 3 types of error.
237
    # IVLEErrors with 4xx response codes (client error).
238
    # IVLEErrors with 5xx response codes (handled server error).
239
    # Other exceptions (unhandled server error).
240
    # IVLEErrors should not have other response codes than 4xx or 5xx
241
    # (eg. throw_redirect should have been used for 3xx codes).
242
    # Therefore, that is treated as an unhandled error.
243
244
    if (exc_type == util.IVLEError and httpcode >= 400
245
        and httpcode <= 499):
246
        # IVLEErrors with 4xx response codes are client errors.
247
        # Therefore, these have a "nice" response (we even coat it in the IVLE
248
        # HTML wrappers).
893 by dcoles
Dispatch: Now attempts to log unhandled exceptions to a log directory specified
249
        
540 by mattgiuca
Refactored error handling and reporting. Much friendlier error messages, for
250
        req.write_html_head_foot = True
251
        req.write('<div id="ivle_padding">\n')
252
        try:
253
            codename, msg = req.get_http_codename(httpcode)
254
        except AttributeError:
255
            codename, msg = None, None
256
        # Override the default message with the supplied one,
257
        # if available.
258
        if exc_value.message is not None:
259
            msg = exc_value.message
260
        if codename is not None:
574 by mattgiuca
dispatch: Error reporting.
261
            req.write("<h1>Error: %s</h1>\n" % cgi.escape(codename))
540 by mattgiuca
Refactored error handling and reporting. Much friendlier error messages, for
262
        else:
263
            req.write("<h1>Error</h1>\n")
264
        if msg is not None:
574 by mattgiuca
dispatch: Error reporting.
265
            req.write("<p>%s</p>\n" % cgi.escape(msg))
540 by mattgiuca
Refactored error handling and reporting. Much friendlier error messages, for
266
        else:
267
            req.write("<p>An unknown error occured.</p>\n")
893 by dcoles
Dispatch: Now attempts to log unhandled exceptions to a log directory specified
268
        
269
        # Logging
270
        logging.info(str(msg))
271
        
540 by mattgiuca
Refactored error handling and reporting. Much friendlier error messages, for
272
        req.write("<p>(HTTP error code %d)</p>\n" % httpcode)
893 by dcoles
Dispatch: Now attempts to log unhandled exceptions to a log directory specified
273
        if logfail:
274
            req.write("<p>Warning: Could not open Error Log: '%s'</p>\n"
275
                %cgi.escape(logfile))
540 by mattgiuca
Refactored error handling and reporting. Much friendlier error messages, for
276
        req.write('</div>\n')
1055 by wagrant
www.dispatch: Don't sent incomplete XHTML for either type of error.
277
        html.write_html_foot(req)
540 by mattgiuca
Refactored error handling and reporting. Much friendlier error messages, for
278
    else:
279
        # A "bad" error message. We shouldn't get here unless IVLE
280
        # misbehaves (which is currently very easy, if things aren't set up
281
        # correctly).
282
        # Write the traceback.
283
        # If this is a non-4xx IVLEError, get the message and httpcode and
284
        # make the error message a bit nicer (but still include the
285
        # traceback).
853 by wagrant
dispatch: Extract exception information from IVLEJailErrors if caught.
286
        # We also need to special-case IVLEJailError, as we can get another
287
        # almost-exception out of it.
288
289
        codename, msg = None, None
290
291
        if exc_type is util.IVLEJailError:
292
            msg = exc_value.type_str + ": " + exc_value.message
293
            tb = 'Exception information extracted from IVLEJailError:\n'
294
            tb += urllib.unquote(exc_value.info)
295
        else:
296
            try:
297
                codename, msg = req.get_http_codename(httpcode)
298
            except AttributeError:
299
                pass
300
            # Override the default message with the supplied one,
301
            # if available.
302
            if hasattr(exc_value, 'message') and exc_value.message is not None:
303
                msg = exc_value.message
304
                # Prepend the exception type
305
                if exc_type != util.IVLEError:
306
                    msg = exc_type.__name__ + ": " + msg
307
308
            tb = ''.join(traceback.format_exception(exc_type, exc_value,
309
                                                    exc_traceback))
852 by wagrant
dispatch: Use a less roundabout way of getting the exception traceback.
310
893 by dcoles
Dispatch: Now attempts to log unhandled exceptions to a log directory specified
311
        # Logging
312
        logging.error('%s\n%s'%(str(msg), tb))
313
1055 by wagrant
www.dispatch: Don't sent incomplete XHTML for either type of error.
314
        req.write("""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"                 
315
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">                                      
316
<html xmlns="http://www.w3.org/1999/xhtml">
540 by mattgiuca
Refactored error handling and reporting. Much friendlier error messages, for
317
<head><title>IVLE Internal Server Error</title></head>
318
<body>
319
<h1>IVLE Internal Server Error""")
320
        if (codename is not None
321
            and httpcode != apache.HTTP_INTERNAL_SERVER_ERROR):
574 by mattgiuca
dispatch: Error reporting.
322
            req.write(": %s" % cgi.escape(codename))
540 by mattgiuca
Refactored error handling and reporting. Much friendlier error messages, for
323
        req.write("""</h1>
324
<p>An error has occured which is the fault of the IVLE developers or
325
administration.</p>
326
""")
327
        if msg is not None:
574 by mattgiuca
dispatch: Error reporting.
328
            req.write("<p>%s</p>\n" % cgi.escape(msg))
540 by mattgiuca
Refactored error handling and reporting. Much friendlier error messages, for
329
        if httpcode is not None:
330
            req.write("<p>(HTTP error code %d)</p>\n" % httpcode)
331
        req.write("""
332
<p>Please report this to <a href="mailto:%s">%s</a> (the system
333
administrator). Include the following information:</p>
574 by mattgiuca
dispatch: Error reporting.
334
""" % (cgi.escape(admin_email), cgi.escape(admin_email)))
540 by mattgiuca
Refactored error handling and reporting. Much friendlier error messages, for
335
893 by dcoles
Dispatch: Now attempts to log unhandled exceptions to a log directory specified
336
        req.write("<pre>\n%s\n</pre>\n"%cgi.escape(tb))
337
        if logfail:
338
            req.write("<p>Warning: Could not open Error Log: '%s'</p>\n"
339
                %cgi.escape(logfile))
1055 by wagrant
www.dispatch: Don't sent incomplete XHTML for either type of error.
340
        req.write("</body></html>")