Code

f1d55180e65c1500889337e9147273d2dc4384e9
[roundup.git] / cgi-bin / roundup.cgi
1 #!/usr/bin/env python
2 #
3 # Copyright (c) 2001 Bizar Software Pty Ltd (http://www.bizarsoftware.com.au/)
4 # This module is free software, and you may redistribute it and/or modify
5 # under the same terms as Python, so long as this copyright message and
6 # disclaimer are retained in their original form.
7 #
8 # IN NO EVENT SHALL BIZAR SOFTWARE PTY LTD BE LIABLE TO ANY PARTY FOR
9 # DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
10 # OUT OF THE USE OF THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE
11 # POSSIBILITY OF SUCH DAMAGE.
12 #
13 # BIZAR SOFTWARE PTY LTD SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
14 # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
15 # FOR A PARTICULAR PURPOSE.  THE CODE PROVIDED HEREUNDER IS ON AN "AS IS"
16 # BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
17 # SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
18
19 # $Id: roundup.cgi,v 1.22 2001-12-13 00:20:01 richard Exp $
21 # python version check
22 from roundup import version_check
24 #
25 ##  Configuration
26 #
28 # Configuration can also be provided through the OS environment (or via
29 # the Apache "SetEnv" configuration directive). If the variables
30 # documented below are set, they _override_ any configuation defaults
31 # given in this file. 
33 # ROUNDUP_INSTANCE_HOMES is a list of instances, in the form
34 # "NAME=DIR<sep>NAME2=DIR2<sep>...", where <sep> is the directory path
35 # separator (";" on Windows, ":" on Unix). 
37 # ROUNDUP_LOG is the name of the logfile; if it's empty or does not exist,
38 # logging is turned off (unless you changed the default below). 
40 # ROUNDUP_DEBUG is a debug level, currently only 0 (OFF) and 1 (ON) are
41 # used in the code. Higher numbers means more debugging output. 
43 # This indicates where the Roundup instance lives
44 ROUNDUP_INSTANCE_HOMES = {
45     'demo': '/var/roundup/instances/demo',
46 }
48 # Where to log debugging information to. Use an instance of DevNull if you
49 # don't want to log anywhere.
50 class DevNull:
51     def write(self, info):
52         pass
53     def close():
54         pass
55 #LOG = open('/var/log/roundup.cgi.log', 'a')
56 LOG = DevNull()
58 #
59 ##  end configuration
60 #
63 #
64 # Set up the error handler
65
66 try:
67     import traceback, StringIO, cgi
68     from roundup import cgitb
69 except:
70     print "Content-Type: text/html\n"
71     print "Failed to import cgitb.<pre>"
72     s = StringIO.StringIO()
73     traceback.print_exc(None, s)
74     print cgi.escape(s.getvalue()), "</pre>"
77 #
78 # Check environment for config items
79 #
80 def checkconfig():
81     import os, string
82     global ROUNDUP_INSTANCE_HOMES, LOG
84     homes = os.environ.get('ROUNDUP_INSTANCE_HOMES', '')
85     if homes:
86         ROUNDUP_INSTANCE_HOMES = {}
87         for home in string.split(homes, os.pathsep):
88             try:
89                 name, dir = string.split(home, '=', 1)
90             except ValueError:
91                 # ignore invalid definitions
92                 continue
93             if name and dir:
94                 ROUNDUP_INSTANCE_HOMES[name] = dir
95                 
96     logname = os.environ.get('ROUNDUP_LOG', '')
97     if logname:
98         LOG = open(logname, 'a')
100     # ROUNDUP_DEBUG is checked directly in "roundup.cgi_client"
104 # Provide interface to CGI HTTP response handling
106 class RequestWrapper:
107     '''Used to make the CGI server look like a BaseHTTPRequestHandler
108     '''
109     def __init__(self, wfile):
110         self.wfile = wfile
111     def write(self, data):
112         self.wfile.write(data)
113     def send_response(self, code):
114         self.write('Status: %s\r\n'%code)
115     def send_header(self, keyword, value):
116         self.write("%s: %s\r\n" % (keyword, value))
117     def end_headers(self):
118         self.write("\r\n")
121 # Main CGI handler
123 def main(out, err):
124     import os, string
125     import roundup.instance
126     path = string.split(os.environ.get('PATH_INFO', '/'), '/')
127     instance = path[1]
128     os.environ['INSTANCE_NAME'] = instance
129     os.environ['PATH_INFO'] = string.join(path[2:], '/')
130     request = RequestWrapper(out)
131     if ROUNDUP_INSTANCE_HOMES.has_key(instance):
132         # redirect if we need a trailing '/'
133         if len(path) == 2:
134             request.send_response(301)
135             absolute_url = 'http://%s%s/'%(os.environ['HTTP_HOST'],
136                 os.environ['REQUEST_URI'])
137             request.send_header('Location', absolute_url)
138             request.end_headers()
139             out.write('Moved Permanently')
140         else:
141             instance_home = ROUNDUP_INSTANCE_HOMES[instance]
142             instance = roundup.instance.open(instance_home)
143             from roundup import cgi_client
144             client = instance.Client(instance, request, os.environ)
145             try:
146                 client.main()
147             except cgi_client.Unauthorised:
148                 request.send_response(403)
149                 request.send_header('Content-Type', 'text/html')
150                 request.end_headers()
151                 out.write('Unauthorised')
152             except cgi_client.NotFound:
153                 request.send_response(404)
154                 request.send_header('Content-Type', 'text/html')
155                 request.end_headers()
156                 out.write('Not found: %s'%client.path)
158     else:
159         import urllib
160         request.send_response(200)
161         request.send_header('Content-Type', 'text/html')
162         request.end_headers()
163         w = request.write
164         w('<html><head><title>Roundup instances index</title></head>\n')
165         w('<body><h1>Roundup instances index</h1><ol>\n')
166         homes = ROUNDUP_INSTANCE_HOMES.keys()
167         homes.sort()
168         for instance in homes:
169             w('<li><a href="%s/%s/index">%s</a>\n'%(
170                 os.environ['SCRIPT_NAME'], urllib.quote(instance),
171                 cgi.escape(instance)))
172         w('</ol></body></html>')
175 # Now do the actual CGI handling
177 out, err = sys.stdout, sys.stderr
178 try:
179     # force input/output to binary (important for file up/downloads)
180     if sys.platform == "win32":
181         import os, msvcrt
182         msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
183         msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
184     checkconfig()
185     sys.stdout = sys.stderr = LOG
186     main(out, err)
187 except SystemExit:
188     pass
189 except:
190     sys.stdout, sys.stderr = out, err
191     out.write('Content-Type: text/html\n\n')
192     cgitb.handler()
193 sys.stdout.flush()
194 sys.stdout, sys.stderr = out, err
195 LOG.close()
198 # $Log: not supported by cvs2svn $
199 # Revision 1.21  2001/12/02 05:06:16  richard
200 # . We now use weakrefs in the Classes to keep the database reference, so
201 #   the close() method on the database is no longer needed.
202 #   I bumped the minimum python requirement up to 2.1 accordingly.
203 # . #487480 ] roundup-server
204 # . #487476 ] INSTALL.txt
206 # I also cleaned up the change message / post-edit stuff in the cgi client.
207 # There's now a clearly marked "TODO: append the change note" where I believe
208 # the change note should be added there. The "changes" list will obviously
209 # have to be modified to be a dict of the changes, or somesuch.
211 # More testing needed.
213 # Revision 1.20  2001/11/26 22:55:56  richard
214 # Feature:
215 #  . Added INSTANCE_NAME to configuration - used in web and email to identify
216 #    the instance.
217 #  . Added EMAIL_SIGNATURE_POSITION to indicate where to place the roundup
218 #    signature info in e-mails.
219 #  . Some more flexibility in the mail gateway and more error handling.
220 #  . Login now takes you to the page you back to the were denied access to.
222 # Fixed:
223 #  . Lots of bugs, thanks Roché and others on the devel mailing list!
225 # Revision 1.19  2001/11/22 00:25:10  richard
226 # quick fix for file uploads on windows in roundup.cgi
228 # Revision 1.18  2001/11/06 22:10:11  jhermann
229 # Added env config; fixed request wrapper & index list; sort list by key
231 # Revision 1.17  2001/11/06 21:51:19  richard
232 # Fixed HTTP headers for top-level index in CGI script
234 # Revision 1.16  2001/11/01 22:04:37  richard
235 # Started work on supporting a pop3-fetching server
236 # Fixed bugs:
237 #  . bug #477104 ] HTML tag error in roundup-server
238 #  . bug #477107 ] HTTP header problem
240 # Revision 1.15  2001/10/29 23:55:44  richard
241 # Fix to CGI top-level index (thanks Juergen Hermann)
243 # Revision 1.14  2001/10/27 00:22:35  richard
244 # Fixed some URL issues in roundup.cgi, again thanks Juergen Hermann.
246 # Revision 1.13  2001/10/05 02:23:24  richard
247 #  . roundup-admin create now prompts for property info if none is supplied
248 #    on the command-line.
249 #  . hyperdb Class getprops() method may now return only the mutable
250 #    properties.
251 #  . Login now uses cookies, which makes it a whole lot more flexible. We can
252 #    now support anonymous user access (read-only, unless there's an
253 #    "anonymous" user, in which case write access is permitted). Login
254 #    handling has been moved into cgi_client.Client.main()
255 #  . The "extended" schema is now the default in roundup init.
256 #  . The schemas have had their page headings modified to cope with the new
257 #    login handling. Existing installations should copy the interfaces.py
258 #    file from the roundup lib directory to their instance home.
259 #  . Incorrectly had a Bizar Software copyright on the cgitb.py module from
260 #    Ping - has been removed.
261 #  . Fixed a whole bunch of places in the CGI interface where we should have
262 #    been returning Not Found instead of throwing an exception.
263 #  . Fixed a deviation from the spec: trying to modify the 'id' property of
264 #    an item now throws an exception.
266 # Revision 1.12  2001/10/01 05:55:41  richard
267 # Fixes to the top-level index
269 # Revision 1.11  2001/09/29 13:27:00  richard
270 # CGI interfaces now spit up a top-level index of all the instances they can
271 # serve.
273 # Revision 1.10  2001/08/07 00:24:42  richard
274 # stupid typo
276 # Revision 1.9  2001/08/07 00:15:51  richard
277 # Added the copyright/license notice to (nearly) all files at request of
278 # Bizar Software.
280 # Revision 1.8  2001/08/05 07:43:52  richard
281 # Instances are now opened by a special function that generates a unique
282 # module name for the instances on import time.
284 # Revision 1.7  2001/08/03 01:28:33  richard
285 # Used the much nicer load_package, pointed out by Steve Majewski.
287 # Revision 1.6  2001/08/03 00:59:34  richard
288 # Instance import now imports the instance using imp.load_module so that
289 # we can have instance homes of "roundup" or other existing python package
290 # names.
292 # Revision 1.5  2001/07/29 07:01:39  richard
293 # Added vim command to all source so that we don't get no steenkin' tabs :)
295 # Revision 1.4  2001/07/23 04:47:27  anthonybaxter
296 # renamed ROUNDUPS to ROUNDUP_INSTANCE_HOMES
297 # sys.exit(0) if python version wrong.
299 # Revision 1.3  2001/07/23 04:33:30  richard
300 # brought the CGI instance config dict in line with roundup-server
302 # Revision 1.2  2001/07/23 04:31:40  richard
303 # Fixed the roundup CGI script for updates to cgi_client.py
305 # Revision 1.1  2001/07/22 11:47:07  richard
306 # More Grande Splite
309 # vim: set filetype=python ts=4 sw=4 et si