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

« back to all changes in this revision

Viewing changes to lib/common/cgirequest.py

  • Committer: Matt Giuca
  • Date: 2010-03-05 07:00:41 UTC
  • Revision ID: matt.giuca@gmail.com-20100305070041-l6z1rfojn78bhiqd
subject.py: Minor refactor in displaying SVN urls. No longer pass the svn root to the Genshi template.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# IVLE - Informatics Virtual Learning Environment
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: cgirequest
19
 
# Author: Matt Giuca
20
 
# Date:   5/2/2007
21
 
 
22
 
# Presents a CGIRequest class which creates an object compatible with IVLE
23
 
# Request objects (the same interface exposed by www.dispatch.request) from a
24
 
# CGI script.
25
 
# This allows CGI scripts to create request objects and then pass them to
26
 
# normal IVLE handlers.
27
 
 
28
 
# NOTE: This object does not support write_html_head_foot (simply because we
29
 
# do not need it in its intended application: fileservice).
30
 
 
31
 
import sys
32
 
import os
33
 
import cgi
34
 
 
35
 
import conf
36
 
import common
37
 
import common.util
38
 
 
39
 
# Utility functions
40
 
 
41
 
def _http_headers_in_from_cgi():
42
 
    """Returns a dictionary of HTTP headers and their values, reading from the
43
 
    CGI environment."""
44
 
    d = {}
45
 
    for k in os.environ.keys():
46
 
        if k.startswith("HTTP_"):
47
 
            # Change the case - underscores become - and each word is
48
 
            # capitalised
49
 
            varname = '-'.join(map(lambda x: x[0:1] + x[1:].lower(),
50
 
                                k[5:].split('_')))
51
 
            d[varname] = os.environ[k]
52
 
    return d
53
 
 
54
 
class CGIRequest:
55
 
    """An IVLE request object, built from a CGI script. This is presented to
56
 
    the IVLE apps as a way of interacting with the CGI server.
57
 
    See dispatch.request for a full interface specification.
58
 
    """
59
 
 
60
 
    # COPIED from dispatch/request.py
61
 
    # Special code for an OK response.
62
 
    # Do not use HTTP_OK; for some reason Apache produces an "OK" error
63
 
    # message if you do that.
64
 
    OK  = 0
65
 
 
66
 
    # HTTP status codes
67
 
 
68
 
    HTTP_CONTINUE                     = 100
69
 
    HTTP_SWITCHING_PROTOCOLS          = 101
70
 
    HTTP_PROCESSING                   = 102
71
 
    HTTP_OK                           = 200
72
 
    HTTP_CREATED                      = 201
73
 
    HTTP_ACCEPTED                     = 202
74
 
    HTTP_NON_AUTHORITATIVE            = 203
75
 
    HTTP_NO_CONTENT                   = 204
76
 
    HTTP_RESET_CONTENT                = 205
77
 
    HTTP_PARTIAL_CONTENT              = 206
78
 
    HTTP_MULTI_STATUS                 = 207
79
 
    HTTP_MULTIPLE_CHOICES             = 300
80
 
    HTTP_MOVED_PERMANENTLY            = 301
81
 
    HTTP_MOVED_TEMPORARILY            = 302
82
 
    HTTP_SEE_OTHER                    = 303
83
 
    HTTP_NOT_MODIFIED                 = 304
84
 
    HTTP_USE_PROXY                    = 305
85
 
    HTTP_TEMPORARY_REDIRECT           = 307
86
 
    HTTP_BAD_REQUEST                  = 400
87
 
    HTTP_UNAUTHORIZED                 = 401
88
 
    HTTP_PAYMENT_REQUIRED             = 402
89
 
    HTTP_FORBIDDEN                    = 403
90
 
    HTTP_NOT_FOUND                    = 404
91
 
    HTTP_METHOD_NOT_ALLOWED           = 405
92
 
    HTTP_NOT_ACCEPTABLE               = 406
93
 
    HTTP_PROXY_AUTHENTICATION_REQUIRED= 407
94
 
    HTTP_REQUEST_TIME_OUT             = 408
95
 
    HTTP_CONFLICT                     = 409
96
 
    HTTP_GONE                         = 410
97
 
    HTTP_LENGTH_REQUIRED              = 411
98
 
    HTTP_PRECONDITION_FAILED          = 412
99
 
    HTTP_REQUEST_ENTITY_TOO_LARGE     = 413
100
 
    HTTP_REQUEST_URI_TOO_LARGE        = 414
101
 
    HTTP_UNSUPPORTED_MEDIA_TYPE       = 415
102
 
    HTTP_RANGE_NOT_SATISFIABLE        = 416
103
 
    HTTP_EXPECTATION_FAILED           = 417
104
 
    HTTP_UNPROCESSABLE_ENTITY         = 422
105
 
    HTTP_LOCKED                       = 423
106
 
    HTTP_FAILED_DEPENDENCY            = 424
107
 
    HTTP_INTERNAL_SERVER_ERROR        = 500
108
 
    HTTP_NOT_IMPLEMENTED              = 501
109
 
    HTTP_BAD_GATEWAY                  = 502
110
 
    HTTP_SERVICE_UNAVAILABLE          = 503
111
 
    HTTP_GATEWAY_TIME_OUT             = 504
112
 
    HTTP_VERSION_NOT_SUPPORTED        = 505
113
 
    HTTP_VARIANT_ALSO_VARIES          = 506
114
 
    HTTP_INSUFFICIENT_STORAGE         = 507
115
 
    HTTP_NOT_EXTENDED                 = 510
116
 
 
117
 
    def __init__(self):
118
 
        """Builds an CGI Request object from the current CGI environment.
119
 
        This results in an object with all of the necessary methods and
120
 
        additional fields.
121
 
        """
122
 
        self.headers_written = False
123
 
 
124
 
        if ('SERVER_NAME' not in os.environ or
125
 
            'REQUEST_METHOD' not in os.environ or
126
 
            'REQUEST_URI' not in os.environ):
127
 
            raise Exception("No CGI environment found")
128
 
 
129
 
        # Determine if the browser used the public host name to make the
130
 
        # request (in which case we are in "public mode")
131
 
        if os.environ['SERVER_NAME'] == conf.public_host:
132
 
            self.publicmode = True
133
 
        else:
134
 
            self.publicmode = False
135
 
 
136
 
        # Inherit values for the input members
137
 
        self.method = os.environ['REQUEST_METHOD']
138
 
        self.uri = os.environ['REQUEST_URI']
139
 
        # Split the given path into the app (top-level dir) and sub-path
140
 
        # (after first stripping away the root directory)
141
 
        path = common.util.unmake_path(self.uri)
142
 
        if self.publicmode:
143
 
            self.app = None
144
 
            self.path = path
145
 
        else:
146
 
            (self.app, self.path) = (common.util.split_path(path))
147
 
        self.username = None
148
 
        self.hostname = os.environ['SERVER_NAME']
149
 
        self.headers_in = _http_headers_in_from_cgi()
150
 
        self.headers_out = {}
151
 
 
152
 
        # Default values for the output members
153
 
        self.status = CGIRequest.HTTP_OK
154
 
        self.content_type = None        # Use Apache's default
155
 
        self.location = None
156
 
        self.title = None     # Will be set by dispatch before passing to app
157
 
        self.styles = []
158
 
        self.scripts = []
159
 
        self.write_html_head_foot = False
160
 
        self.got_common_vars = False
161
 
 
162
 
    def __writeheaders(self):
163
 
        """Writes out the HTTP and HTML headers before any real data is
164
 
        written."""
165
 
        self.headers_written = True
166
 
        if 'Content-Type' in self.headers_out:
167
 
            self.content_type = self.headers_out['Content-Type']
168
 
        if 'Location' in self.headers_out:
169
 
            self.location = self.headers_out['Location']
170
 
 
171
 
        # CGI allows for four response types: Document, Local Redirect, Client
172
 
        # Redirect, and Client Redirect w/ Document
173
 
        # XXX We do not allow Local Redirect
174
 
        if self.location != None:
175
 
            # This is a Client Redirect
176
 
            print "Location: %s" % self.location
177
 
            if self.content_type == None:
178
 
                # Just redirect
179
 
                return
180
 
            # Else: This is a Client Redirect with Document
181
 
            print "Status: %d" % self.status
182
 
            print "Content-Type: %s" % self.content_type
183
 
        else:
184
 
            # This is a Document response
185
 
            print "Content-Type: %s" % self.content_type
186
 
            print "Status: %d" % self.status
187
 
 
188
 
        # Print the other headers
189
 
        for k,v in self.headers_out.items():
190
 
            if k != 'Content-Type' and k != 'Location':
191
 
                print "%s: %s" % (k, v)
192
 
 
193
 
        # XXX write_html_head_foot not supported
194
 
        #if self.write_html_head_foot:
195
 
        #    # Write the HTML header, pass "self" (request object)
196
 
        #    self.func_write_html_head(self)
197
 
        # Print a blank line to signal the start of output
198
 
        print
199
 
 
200
 
    def ensure_headers_written(self):
201
 
        """Writes out the HTTP and HTML headers if they haven't already been
202
 
        written."""
203
 
        if not self.headers_written:
204
 
            self.__writeheaders()
205
 
 
206
 
    def write(self, string, flush=1):
207
 
        """Writes string directly to the client, then flushes the buffer,
208
 
        unless flush is 0."""
209
 
 
210
 
        if not self.headers_written:
211
 
            self.__writeheaders()
212
 
        if isinstance(string, unicode):
213
 
            # Encode unicode strings as UTF-8
214
 
            # (Otherwise cannot handle being written to a bytestream)
215
 
            sys.stdout.write(string.encode('utf8'))
216
 
        else:
217
 
            # 8-bit clean strings just get written directly.
218
 
            # This includes binary strings.
219
 
            sys.stdout.write(string)
220
 
 
221
 
    def flush(self):
222
 
        """Flushes the output buffer."""
223
 
        sys.stdout.flush()
224
 
 
225
 
    def sendfile(self, filename):
226
 
        """Sends the named file directly to the client."""
227
 
        if not self.headers_written:
228
 
            self.__writeheaders()
229
 
        f = open(filename)
230
 
        buf = f.read(1024)
231
 
        while len(buf) > 0:
232
 
            sys.stdout.flush(buf)
233
 
            buf = f.read(1024)
234
 
        f.close()
235
 
 
236
 
    def read(self, len=None):
237
 
        """Reads at most len bytes directly from the client. (See mod_python
238
 
        Request.read)."""
239
 
        if len is None:
240
 
            return sys.stdin.read()
241
 
        else:
242
 
            return sys.stdin.read(len)
243
 
 
244
 
    def throw_error(self, httpcode):
245
 
        """Writes out an HTTP error of the specified code. Exits the process,
246
 
        so any code following this call will not be executed.
247
 
 
248
 
        (This is justified because of the nature of CGI, it is a single-script
249
 
        environment, there is no containing process which needs to catch an
250
 
        exception).
251
 
 
252
 
        httpcode: An HTTP response status code. Pass a constant from the
253
 
        Request class.
254
 
        """
255
 
        self.status = httpcode
256
 
        self.content_type = "text/html"
257
 
        # Emulate an Apache error
258
 
        self.write("""<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
259
 
<html><head>
260
 
<title>%d Error</title>
261
 
</head><body>
262
 
<h1>Error</h1>
263
 
<p>A %d error was triggered by a CGI app.</p>
264
 
</body></html>
265
 
""" % (httpcode, httpcode))
266
 
        # Exit the process completely
267
 
        self.flush()
268
 
        sys.exit(httpcode)
269
 
 
270
 
    def throw_redirect(self, location):
271
 
        """Writes out an HTTP redirect to the specified URL. Exits the
272
 
        process, so any code following this call will not be executed.
273
 
 
274
 
        httpcode: An HTTP response status code. Pass a constant from the
275
 
        Request class.
276
 
        """
277
 
        self.status = CGIRequest.HTTP_MOVED_TEMPORARILY
278
 
        self.location = location
279
 
        self.ensure_headers_written()
280
 
        self.flush()
281
 
        sys.exit(self.status)
282
 
 
283
 
    def get_session(self):
284
 
        """Returns a mod_python Session object for this request.
285
 
        Note that this is dependent on mod_python and may need to change
286
 
        interface if porting away from mod_python."""
287
 
        # Cache the session object
288
 
        if not hasattr(self, 'session'):
289
 
            #self.session = Session.FileSession(self.apache_req)
290
 
            self.session = None
291
 
            # FIXME: How to get session?
292
 
        return self.session
293
 
 
294
 
    def get_fieldstorage(self):
295
 
        """Returns a mod_python FieldStorage object for this request.
296
 
        Note that this is dependent on mod_python and may need to change
297
 
        interface if porting away from mod_python."""
298
 
        # Cache the fieldstorage object
299
 
        if not hasattr(self, 'fields'):
300
 
            self.fields = cgi.FieldStorage()
301
 
        return self.fields
302
 
 
303
 
    def get_cgi_environ(self):
304
 
        """Returns the CGI environment emulation for this request. (Calls
305
 
        add_common_vars). The environment is returned as a mapping
306
 
        compatible with os.environ."""
307
 
        return os.environ