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

« back to all changes in this revision

Viewing changes to ivle/dispatch/__init__.py

Remove the last two uses of req.write_html_head_foot.

Show diffs side-by-side

added added

removed removed

Lines of Context:
22
22
Apache send all requests to be handled by the module 'dispatch'.
23
23
 
24
24
Top-level handler. Handles all requests to all pages in IVLE.
25
 
Handles authentication and delegates to views for authorization,
26
 
then passes the request along to the appropriate view.
 
25
Handles authentication (not authorization).
 
26
Then passes the request along to the appropriate ivle app.
27
27
"""
28
28
 
29
29
import sys
42
42
from ivle import util
43
43
import ivle.conf
44
44
from ivle.dispatch.request import Request
45
 
import ivle.webapp.security
 
45
from ivle.dispatch import login
46
46
from ivle.webapp.base.plugins import ViewPlugin, PublicViewPlugin
47
 
from ivle.webapp.base.xhtml import XHTMLView, XHTMLErrorView
48
 
from ivle.webapp.errors import HTTPError, Unauthorized, NotFound
 
47
from ivle.webapp.errors import HTTPError, Unauthorized
 
48
import html
49
49
 
50
50
def generate_route_mapper(view_plugins, attr):
51
51
    """
63
63
            m.connect(routex, view=view_class, **kwargs_dict)
64
64
    return m
65
65
 
66
 
def handler(apachereq):
67
 
    """Handles an HTTP request.
68
 
 
 
66
def handler(req):
 
67
    """Handles a request which may be to anywhere in the site except media.
69
68
    Intended to be called by mod_python, as a handler.
70
69
 
71
 
    @param apachereq: An Apache request object.
72
 
    """
73
 
    # Make the request object into an IVLE request which can be given to views
74
 
    req = Request(apachereq)
75
 
 
 
70
    req: An Apache request object.
 
71
    """
 
72
    # Make the request object into an IVLE request which can be passed to apps
 
73
    apachereq = req
 
74
    try:
 
75
        req = Request(req, html.write_html_head)
 
76
    except Exception:
 
77
        # Pass the apachereq to error reporter, since ivle req isn't created
 
78
        # yet.
 
79
        handle_unknown_exception(apachereq, *sys.exc_info())
 
80
        # Tell Apache not to generate its own errors as well
 
81
        return mod_python.apache.OK
 
82
 
 
83
    # Run the main handler, and catch all exceptions
 
84
    try:
 
85
        return handler_(req, apachereq)
 
86
    except mod_python.apache.SERVER_RETURN:
 
87
        # An apache error. We discourage these, but they might still happen.
 
88
        # Just raise up.
 
89
        raise
 
90
    except Exception:
 
91
        handle_unknown_exception(req, *sys.exc_info())
 
92
        # Tell Apache not to generate its own errors as well
 
93
        return mod_python.apache.OK
 
94
 
 
95
def handler_(req, apachereq):
 
96
    """
 
97
    Nested handler function. May raise exceptions. The top-level handler is
 
98
    just used to catch exceptions.
 
99
    Takes both an IVLE request and an Apache req.
 
100
    """
76
101
    # Hack? Try and get the user login early just in case we throw an error
77
102
    # (most likely 404) to stop us seeing not logged in even when we are.
78
103
    if not req.publicmode:
79
 
        user = ivle.webapp.security.get_user_details(req)
 
104
        user = login.get_user_details(req)
80
105
 
81
106
        # Don't set the user if it is disabled or hasn't accepted the ToS.
82
107
        if user and user.valid:
117
142
            if hasattr(viewcls, 'get_error_view'):
118
143
                errviewcls = viewcls.get_error_view(e)
119
144
            else:
120
 
                errviewcls = XHTMLView.get_error_view(e)
 
145
                errviewcls = None
121
146
 
122
147
            if errviewcls:
123
148
                errview = errviewcls(req, e)
136
161
            req.store.commit()
137
162
            return req.OK
138
163
    else:
139
 
        XHTMLErrorView(req, NotFound()).render(req)
140
 
        return req.OK
 
164
        return req.HTTP_NOT_FOUND # TODO: Prettify.
141
165
 
142
166
def handle_unknown_exception(req, exc_type, exc_value, exc_traceback):
143
167
    """
152
176
    req.content_type = "text/html"
153
177
    logfile = os.path.join(ivle.conf.log_path, 'ivle_error.log')
154
178
    logfail = False
 
179
    # For some reason, some versions of mod_python have "_server" instead of
 
180
    # "main_server". So we check for both.
 
181
    try:
 
182
        admin_email = mod_python.apache.main_server.server_admin
 
183
    except AttributeError:
 
184
        try:
 
185
            admin_email = mod_python.apache._server.server_admin
 
186
        except AttributeError:
 
187
            admin_email = ""
155
188
    try:
156
189
        httpcode = exc_value.httpcode
157
190
        req.status = httpcode
166
199
        login = req.user.login
167
200
    except AttributeError:
168
201
        login = None
 
202
    try:
 
203
        role = req.user.role
 
204
    except AttributeError:
 
205
        role = None
169
206
 
170
207
    # Log File
171
208
    try:
181
218
            filemode='a')
182
219
    except IOError:
183
220
        logfail = True
 
221
    logging.debug('Logging Unhandled Exception')
184
222
 
185
223
    # A "bad" error message. We shouldn't get here unless IVLE
186
224
    # misbehaves (which is currently very easy, if things aren't set up
203
241
            codename, msg = req.get_http_codename(httpcode)
204
242
        except AttributeError:
205
243
            pass
 
244
        # Override the default message with the supplied one,
 
245
        # if available.
 
246
        if hasattr(exc_value, 'message') and exc_value.message is not None:
 
247
            msg = exc_value.message
 
248
            # Prepend the exception type
 
249
            if exc_type != util.IVLEError:
 
250
                msg = exc_type.__name__ + ": " + repr(msg)
206
251
 
207
252
        tb = ''.join(traceback.format_exception(exc_type, exc_value,
208
253
                                                exc_traceback))
209
254
 
 
255
    # Logging
210
256
    logging.error('%s\n%s'%(str(msg), tb))
211
 
 
212
257
    # Error messages are only displayed is the user is NOT a student,
213
258
    # or if there has been a problem logging the error message
214
 
    show_errors = (not publicmode) and ((login and req.user.admin) or logfail)
 
259
    show_errors = (not publicmode) and ((login and \
 
260
                        str(role) != "student") or logfail)
215
261
    req.write("""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"                 
216
262
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">                                      
217
263
<html xmlns="http://www.w3.org/1999/xhtml">
218
264
<head><title>IVLE Internal Server Error</title></head>
219
265
<body>
220
266
<h1>IVLE Internal Server Error""")
221
 
    if show_errors:
222
 
        if codename is not None and \
223
 
           httpcode != mod_python.apache.HTTP_INTERNAL_SERVER_ERROR:
 
267
    if (show_errors):
 
268
        if (codename is not None
 
269
                    and httpcode != mod_python.apache.HTTP_INTERNAL_SERVER_ERROR):
224
270
            req.write(": %s" % cgi.escape(codename))
225
271
 
226
272
    req.write("""</h1>
227
273
<p>An error has occured which is the fault of the IVLE developers or
228
 
administrators. """)
229
 
 
230
 
    if logfail:
231
 
        req.write("Please report this issue to the server administrators, "
232
 
                  "along with the following information.")
233
 
    else:
234
 
        req.write("Details have been logged for further examination.")
235
 
    req.write("</p>")
236
 
 
237
 
    if show_errors:
 
274
administration. The developers have been notified.</p>
 
275
""")
 
276
    if (show_errors):
238
277
        if msg is not None:
239
278
            req.write("<p>%s</p>\n" % cgi.escape(msg))
240
279
        if httpcode is not None:
241
280
            req.write("<p>(HTTP error code %d)</p>\n" % httpcode)
242
 
        req.write("<h2>Debugging information</h2>")
 
281
        req.write("""
 
282
<p>Please report this to <a href="mailto:%s">%s</a> (the system
 
283
administrator). Include the following information:</p>
 
284
""" % (cgi.escape(admin_email), cgi.escape(admin_email)))
243
285
 
244
286
        req.write("<pre>\n%s\n</pre>\n"%cgi.escape(tb))
 
287
        if logfail:
 
288
            req.write("<p>Warning: Could not open Error Log: '%s'</p>\n"
 
289
                %cgi.escape(logfile))
245
290
    req.write("</body></html>")