Code

. web forms may now unset Link values (like assignedto)
[roundup.git] / roundup / cgi_client.py
1 #
2 # Copyright (c) 2001 Bizar Software Pty Ltd (http://www.bizarsoftware.com.au/)
3 # This module is free software, and you may redistribute it and/or modify
4 # under the same terms as Python, so long as this copyright message and
5 # disclaimer are retained in their original form.
6 #
7 # IN NO EVENT SHALL BIZAR SOFTWARE PTY LTD BE LIABLE TO ANY PARTY FOR
8 # DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
9 # OUT OF THE USE OF THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE
10 # POSSIBILITY OF SUCH DAMAGE.
11 #
12 # BIZAR SOFTWARE PTY LTD SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
13 # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
14 # FOR A PARTICULAR PURPOSE.  THE CODE PROVIDED HEREUNDER IS ON AN "AS IS"
15 # BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
16 # SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
17
18 # $Id: cgi_client.py,v 1.154 2002-07-31 23:57:36 richard Exp $
20 __doc__ = """
21 WWW request handler (also used in the stand-alone server).
22 """
24 import os, cgi, StringIO, urlparse, re, traceback, mimetypes, urllib
25 import binascii, Cookie, time, random
27 import roundupdb, htmltemplate, date, hyperdb, password
28 from roundup.i18n import _
30 class Unauthorised(ValueError):
31     pass
33 class NotFound(ValueError):
34     pass
36 def initialiseSecurity(security):
37     ''' Create some Permissions and Roles on the security object
39         This function is directly invoked by security.Security.__init__()
40         as a part of the Security object instantiation.
41     '''
42     security.addPermission(name="Web Registration",
43         description="User may register through the web")
45     # doing Role stuff through the web - make sure Admin can
46     p = security.addPermission(name="Web Roles",
47         description="User may manipulate user Roles through the web")
48     security.addPermissionToRole('Admin', p)
50 class Client:
51     '''
52     A note about login
53     ------------------
55     If the user has no login cookie, then they are anonymous. There
56     are two levels of anonymous use. If there is no 'anonymous' user, there
57     is no login at all and the database is opened in read-only mode. If the
58     'anonymous' user exists, the user is logged in using that user (though
59     there is no cookie). This allows them to modify the database, and all
60     modifications are attributed to the 'anonymous' user.
62     Once a user logs in, they are assigned a session. The Client instance
63     keeps the nodeid of the session as the "session" attribute.
64     '''
66     def __init__(self, instance, request, env, form=None):
67         hyperdb.traceMark()
68         self.instance = instance
69         self.request = request
70         self.env = env
71         self.path = env['PATH_INFO']
72         self.split_path = self.path.split('/')
73         self.instance_path_name = env['INSTANCE_NAME']
74         url = self.env['SCRIPT_NAME'] + '/'
75         machine = self.env['SERVER_NAME']
76         port = self.env['SERVER_PORT']
77         if port != '80': machine = machine + ':' + port
78         self.base = urlparse.urlunparse(('http', env['HTTP_HOST'], url,
79             None, None, None))
81         if form is None:
82             self.form = cgi.FieldStorage(environ=env)
83         else:
84             self.form = form
85         self.headers_done = 0
86         try:
87             self.debug = int(env.get("ROUNDUP_DEBUG", 0))
88         except ValueError:
89             # someone gave us a non-int debug level, turn it off
90             self.debug = 0
92     def getuid(self):
93         try:
94             return self.db.user.lookup(self.user)
95         except KeyError:
96             if self.user is None:
97                 # user is not logged in and username 'anonymous' doesn't
98                 # exist in the database
99                 err = _('anonymous users have read-only access only')
100             else:
101                 err = _("sanity check: unknown user name `%s'")%self.user
102             raise Unauthorised, errmsg
104     def header(self, headers=None, response=200):
105         '''Put up the appropriate header.
106         '''
107         if headers is None:
108             headers = {'Content-Type':'text/html'}
109         if not headers.has_key('Content-Type'):
110             headers['Content-Type'] = 'text/html'
111         self.request.send_response(response)
112         for entry in headers.items():
113             self.request.send_header(*entry)
114         self.request.end_headers()
115         self.headers_done = 1
116         if self.debug:
117             self.headers_sent = headers
119     global_javascript = '''
120 <script language="javascript">
121 submitted = false;
122 function submit_once() {
123     if (submitted) {
124         alert("Your request is being processed.\\nPlease be patient.");
125         return 0;
126     }
127     submitted = true;
128     return 1;
131 function help_window(helpurl, width, height) {
132     HelpWin = window.open('%(base)s%(instance_path_name)s/' + helpurl, 'RoundupHelpWindow', 'scrollbars=yes,resizable=yes,toolbar=no,height='+height+',width='+width);
135 </script>
136 '''
137     def make_index_link(self, name):
138         '''Turn a configuration entry into a hyperlink...
139         '''
140         # get the link label and spec
141         spec = getattr(self.instance, name+'_INDEX')
143         d = {}
144         d[':sort'] = ','.join(map(urllib.quote, spec['SORT']))
145         d[':group'] = ','.join(map(urllib.quote, spec['GROUP']))
146         d[':filter'] = ','.join(map(urllib.quote, spec['FILTER']))
147         d[':columns'] = ','.join(map(urllib.quote, spec['COLUMNS']))
148         d[':pagesize'] = spec.get('PAGESIZE','50')
150         # snarf the filterspec
151         filterspec = spec['FILTERSPEC'].copy()
153         # now format the filterspec
154         for k, l in filterspec.items():
155             # fix up the CURRENT USER if needed (handle None too since that's
156             # the old flag value)
157             if l in (None, 'CURRENT USER'):
158                 if not self.user:
159                     continue
160                 l = [self.db.user.lookup(self.user)]
162             # add
163             d[urllib.quote(k)] = ','.join(map(urllib.quote, l))
165         # finally, format the URL
166         return '<a href="%s?%s">%s</a>'%(spec['CLASS'],
167             '&'.join([k+'='+v for k,v in d.items()]), spec['LABEL'])
170     def pagehead(self, title, message=None):
171         '''Display the page heading, with information about the tracker and
172             links to more information
173         '''
175         # include any important message
176         if message is not None:
177             message = _('<div class="system-msg">%(message)s</div>')%locals()
178         else:
179             message = ''
181         # style sheet (CSS)
182         style = open(os.path.join(self.instance.TEMPLATES, 'style.css')).read()
184         # figure who the user is
185         user_name = self.user
186         userid = self.db.user.lookup(user_name)
188         # figure all the header links
189         if hasattr(self.instance, 'HEADER_INDEX_LINKS'):
190             links = []
191             for name in self.instance.HEADER_INDEX_LINKS:
192                 spec = getattr(self.instance, name + '_INDEX')
193                 # skip if we need to fill in the logged-in user id and
194                 # we're anonymous
195                 if (spec['FILTERSPEC'].has_key('assignedto') and
196                         spec['FILTERSPEC']['assignedto'] in ('CURRENT USER',
197                         None) and user_name == 'anonymous'):
198                     continue
199                 links.append(self.make_index_link(name))
200         else:
201             # no config spec - hard-code
202             links = [
203                 _('All <a href="issue?status=-1,unread,deferred,chatting,need-eg,in-progress,testing,done-cbb&:sort=-activity&:filter=status&:columns=id,activity,status,title,assignedto&:group=priority&show_customization=1">Issues</a>'),
204                 _('Unassigned <a href="issue?assignedto=-1&status=-1,unread,deferred,chatting,need-eg,in-progress,testing,done-cbb&:sort=-activity&:filter=status,assignedto&:columns=id,activity,status,title,assignedto&:group=priority&show_customization=1">Issues</a>')
205             ]
207         user_info = _('<a href="login">Login</a>')
208         add_links = ''
209         if user_name != 'anonymous':
210             # add any personal queries to the menu
211             try:
212                 queries = self.db.getclass('query')
213             except KeyError:
214                 # no query class
215                 queries = self.instance.dbinit.Class(self.db, "query",
216                     klass=hyperdb.String(), name=hyperdb.String(),
217                     url=hyperdb.String())
218                 queries.setkey('name')
219                 #queries.disableJournalling()
220             try:
221                 qids = self.db.getclass('user').get(userid, 'queries')
222             except KeyError, e:
223                 #self.db.getclass('user').addprop(queries=hyperdb.Multilink('query'))
224                 qids = []
225             for qid in qids:
226                 links.append('<a href=%s?%s>%s</a>'%(queries.get(qid, 'klass'),
227                     queries.get(qid, 'url'), queries.get(qid, 'name')))
229             # if they're logged in, include links to their information,
230             # and the ability to add an issue
231             user_info = _('''
232 <a href="user%(userid)s">My Details</a> | <a href="logout">Logout</a>
233 ''')%locals()
235         # figure the "add class" links
236         if hasattr(self.instance, 'HEADER_ADD_LINKS'):
237             classes = self.instance.HEADER_ADD_LINKS
238         else:
239             classes = ['issue']
240         l = []
241         for class_name in classes:
242             # make sure the user has permission to add
243             if not self.db.security.hasPermission('Edit', userid, class_name):
244                 continue
245             cap_class = class_name.capitalize()
246             links.append(_('Add <a href="new%(class_name)s">'
247                 '%(cap_class)s</a>')%locals())
249         # if the user can edit everything, include the links
250         admin_links = ''
251         userid = self.db.user.lookup(user_name)
252         if self.db.security.hasPermission('Edit', userid):
253             links.append(_('<a href="list_classes">Class List</a>'))
254             links.append(_('<a href="user?:sort=username&:group=roles">User List</a>'))
255             links.append(_('<a href="newuser">Add User</a>'))
257         # add the search links
258         if hasattr(self.instance, 'HEADER_SEARCH_LINKS'):
259             classes = self.instance.HEADER_SEARCH_LINKS
260         else:
261             classes = ['issue']
262         l = []
263         for class_name in classes:
264             # make sure the user has permission to view
265             if not self.db.security.hasPermission('View', userid, class_name):
266                 continue
267             cap_class = class_name.capitalize()
268             links.append(_('Search <a href="search%(class_name)s">'
269                 '%(cap_class)s</a>')%locals())
271         # now we have all the links, join 'em
272         links = '\n | '.join(links)
274         # include the javascript bit
275         global_javascript = self.global_javascript%self.__dict__
277         # finally, format the header
278         self.write(_('''<html><head>
279 <title>%(title)s</title>
280 <style type="text/css">%(style)s</style>
281 </head>
282 %(global_javascript)s
283 <body bgcolor=#ffffff>
284 %(message)s
285 <table width=100%% border=0 cellspacing=0 cellpadding=2>
286  <tr class="location-bar">
287   <td><big><strong>%(title)s</strong></big></td>
288   <td align=right valign=bottom>%(user_name)s</td>
289  </tr>
290  <tr class="location-bar">
291   <td align=left>%(links)s</td>
292   <td align=right>%(user_info)s</td>
293  </tr>
294 </table><br>
295 ''')%locals())
297     def pagefoot(self):
298         if self.debug:
299             self.write(_('<hr><small><dl><dt><b>Path</b></dt>'))
300             self.write('<dd>%s</dd>'%(', '.join(map(repr, self.split_path))))
301             keys = self.form.keys()
302             keys.sort()
303             if keys:
304                 self.write(_('<dt><b>Form entries</b></dt>'))
305                 for k in self.form.keys():
306                     v = self.form.getvalue(k, "<empty>")
307                     if type(v) is type([]):
308                         # Multiple username fields specified
309                         v = "|".join(v)
310                     self.write('<dd><em>%s</em>=%s</dd>'%(k, cgi.escape(v)))
311             keys = self.headers_sent.keys()
312             keys.sort()
313             self.write(_('<dt><b>Sent these HTTP headers</b></dt>'))
314             for k in keys:
315                 v = self.headers_sent[k]
316                 self.write('<dd><em>%s</em>=%s</dd>'%(k, cgi.escape(v)))
317             keys = self.env.keys()
318             keys.sort()
319             self.write(_('<dt><b>CGI environment</b></dt>'))
320             for k in keys:
321                 v = self.env[k]
322                 self.write('<dd><em>%s</em>=%s</dd>'%(k, cgi.escape(v)))
323             self.write('</dl></small>')
324         self.write('</body></html>')
326     def write(self, content):
327         if not self.headers_done:
328             self.header()
329         self.request.wfile.write(content)
331     def index_arg(self, arg):
332         ''' handle the args to index - they might be a list from the form
333             (ie. submitted from a form) or they might be a command-separated
334             single string (ie. manually constructed GET args)
335         '''
336         if self.form.has_key(arg):
337             arg =  self.form[arg]
338             if type(arg) == type([]):
339                 return [arg.value for arg in arg]
340             return arg.value.split(',')
341         return []
343     def index_sort(self):
344         # first try query string
345         x = self.index_arg(':sort')
346         if x:
347             return x
348         # nope - get the specs out of the form
349         specs = []
350         for colnm in self.db.getclass(self.classname).getprops().keys():
351             desc = ''
352             try:
353                 spec = self.form[':%s_ss' % colnm]
354             except KeyError:
355                 continue
356             spec = spec.value
357             if spec:
358                 if spec[-1] == '-':
359                     desc='-'
360                     spec = spec[0]
361                 specs.append((int(spec), colnm, desc))
362         specs.sort()
363         x = []
364         for _, colnm, desc in specs:
365             x.append('%s%s' % (desc, colnm))
366         return x
367     
368     def index_filterspec(self, filter, classname=None):
369         ''' pull the index filter spec from the form
371         Links and multilinks want to be lists - the rest are straight
372         strings.
373         '''
374         if classname is None:
375             classname = self.classname
376         klass = self.db.getclass(classname)
377         filterspec = {}
378         props = klass.getprops()
379         for colnm in filter:
380             widget = ':%s_fs' % colnm
381             try:
382                 val = self.form[widget]
383             except KeyError:
384                 try:
385                     val = self.form[colnm]
386                 except KeyError:
387                     # they checked the filter box but didn't enter a value
388                     continue
389             propdescr = props.get(colnm, None)
390             if propdescr is None:
391                 print "huh? %r is in filter & form, but not in Class!" % colnm
392                 raise "butthead programmer"
393             if (isinstance(propdescr, hyperdb.Link) or
394                 isinstance(propdescr, hyperdb.Multilink)):
395                 if type(val) == type([]):
396                     val = [arg.value for arg in val]
397                 else:
398                     val = val.value.split(',')
399                 l = filterspec.get(colnm, [])
400                 l = l + val
401                 filterspec[colnm] = l
402             else:
403                 filterspec[colnm] = val.value
404             
405         return filterspec
406     
407     def customization_widget(self):
408         ''' The customization widget is visible by default. The widget
409             visibility is remembered by show_customization.  Visibility
410             is not toggled if the action value is "Redisplay"
411         '''
412         if not self.form.has_key('show_customization'):
413             visible = 1
414         else:
415             visible = int(self.form['show_customization'].value)
416             if self.form.has_key('action'):
417                 if self.form['action'].value != 'Redisplay':
418                     visible = self.form['action'].value == '+'
419             
420         return visible
422     # TODO: make this go away some day...
423     default_index_sort = ['-activity']
424     default_index_group = ['priority']
425     default_index_filter = ['status']
426     default_index_columns = ['id','activity','title','status','assignedto']
427     default_index_filterspec = {'status': ['1', '2', '3', '4', '5', '6', '7']}
428     default_pagesize = '50'
430     def _get_customisation_info(self):
431         # see if the web has supplied us with any customisation info
432         for key in ':sort', ':group', ':filter', ':columns', ':pagesize':
433             if self.form.has_key(key):
434                 # make list() extract the info from the CGI environ
435                 self.classname = 'issue'
436                 sort = group = filter = columns = filterspec = pagesize = None
437                 break
438         else:
439             # TODO: look up the session first
440             # try the instance config first
441             if hasattr(self.instance, 'DEFAULT_INDEX'):
442                 d = self.instance.DEFAULT_INDEX
443                 self.classname = d['CLASS']
444                 sort = d['SORT']
445                 group = d['GROUP']
446                 filter = d['FILTER']
447                 columns = d['COLUMNS']
448                 filterspec = d['FILTERSPEC']
449                 pagesize = d.get('PAGESIZE', '50')
450             else:
451                 # nope - fall back on the old way of doing it
452                 self.classname = 'issue'
453                 sort = self.default_index_sort
454                 group = self.default_index_group
455                 filter = self.default_index_filter
456                 columns = self.default_index_columns
457                 filterspec = self.default_index_filterspec
458                 pagesize = self.default_pagesize
459         return columns, filter, group, sort, filterspec, pagesize
461     def index(self):
462         ''' put up an index - no class specified
463         '''
464         columns, filter, group, sort, filterspec, pagesize = \
465             self._get_customisation_info()
466         return self.list(columns=columns, filter=filter, group=group,
467             sort=sort, filterspec=filterspec, pagesize=pagesize)
469     def searchnode(self):
470         columns, filter, group, sort, filterspec, pagesize = \
471             self._get_customisation_info()
472         cn = self.classname
473         self.pagehead(_('%(instancename)s: Index of %(classname)s')%{
474             'classname': cn, 'instancename': self.instance.INSTANCE_NAME})
475         index = htmltemplate.IndexTemplate(self, self.instance.TEMPLATES, cn)
476         self.write('<form onSubmit="return submit_once()" action="%s">\n'%self.classname)
477         all_columns = self.db.getclass(cn).getprops().keys()
478         all_columns.sort()
479         index.filter_section('', filter, columns, group, all_columns, sort,
480                              filterspec, pagesize, 0)
481         self.pagefoot()
482         index.db = index.cl = index.properties = None
483         index.clear()
485     # XXX deviates from spec - loses the '+' (that's a reserved character
486     # in URLS
487     def list(self, sort=None, group=None, filter=None, columns=None,
488             filterspec=None, show_customization=None, show_nodes=1,
489             pagesize=None):
490         ''' call the template index with the args
492             :sort    - sort by prop name, optionally preceeded with '-'
493                      to give descending or nothing for ascending sorting.
494             :group   - group by prop name, optionally preceeded with '-' or
495                      to sort in descending or nothing for ascending order.
496             :filter  - selects which props should be displayed in the filter
497                      section. Default is all.
498             :columns - selects the columns that should be displayed.
499                      Default is all.
501         '''
502         cn = self.classname
503         cl = self.db.classes[cn]
504         if sort is None: sort = self.index_sort()
505         if group is None: group = self.index_arg(':group')
506         if filter is None: filter = self.index_arg(':filter')
507         if columns is None: columns = self.index_arg(':columns')
508         if filterspec is None: filterspec = self.index_filterspec(filter)
509         if show_customization is None:
510             show_customization = self.customization_widget()
511         if self.form.has_key('search_text'):
512             search_text = self.form['search_text'].value
513         else:
514             search_text = ''
515         if pagesize is None:
516             if self.form.has_key(':pagesize'):
517                 pagesize = self.form[':pagesize'].value
518             else:
519                 pagesize = '50'
520         pagesize = int(pagesize)
521         if self.form.has_key(':startwith'):
522             startwith = int(self.form[':startwith'].value)
523         else:
524             startwith = 0
526         if self.form.has_key('Query') and self.form['Query'].value == 'Save':
527             # format a query string
528             qd = {}
529             qd[':sort'] = ','.join(map(urllib.quote, sort))
530             qd[':group'] = ','.join(map(urllib.quote, group))
531             qd[':filter'] = ','.join(map(urllib.quote, filter))
532             qd[':columns'] = ','.join(map(urllib.quote, columns))
533             for k, l in filterspec.items():
534                 qd[urllib.quote(k)] = ','.join(map(urllib.quote, l))
535             url = '&'.join([k+'='+v for k,v in qd.items()])
536             url += '&:pagesize=%s' % pagesize
537             if search_text:
538                 url += '&search_text=%s' % search_text
540             # create a query
541             d = {}
542             d['name'] = nm = self.form[':name'].value
543             if not nm:
544                 d['name'] = nm = 'New Query'
545             d['klass'] = self.form[':classname'].value
546             d['url'] = url
547             qid = self.db.getclass('query').create(**d)
549             # and add it to the user's query multilink
550             uid = self.getuid()
551             usercl = self.db.getclass('user')
552             queries = usercl.get(uid, 'queries')
553             queries.append(qid)
554             usercl.set(uid, queries=queries)
555             
556         self.pagehead(_('%(instancename)s: Index of %(classname)s')%{
557             'classname': cn, 'instancename': self.instance.INSTANCE_NAME})
558         
559         index = htmltemplate.IndexTemplate(self, self.instance.TEMPLATES, cn)
560         try:
561             index.render(filterspec, search_text, filter, columns, sort, 
562                 group, show_customization=show_customization, 
563                 show_nodes=show_nodes, pagesize=pagesize, startwith=startwith)
564         except htmltemplate.MissingTemplateError:
565             self.basicClassEditPage()
566         self.pagefoot()
568     def basicClassEditPage(self):
569         '''Display a basic edit page that allows simple editing of the
570            nodes of the current class
571         '''
572         userid = self.db.user.lookup(self.user)
573         if not self.db.security.hasPermission('Edit', userid):
574             raise Unauthorised, _("You do not have permission to access"\
575                         " %(action)s.")%{'action': self.classname}
576         w = self.write
577         cn = self.classname
578         cl = self.db.classes[cn]
579         idlessprops = cl.getprops(protected=0).keys()
580         props = ['id'] + idlessprops
582         # get the CSV module
583         try:
584             import csv
585         except ImportError:
586             w(_('Sorry, you need the csv module to use this function.<br>\n'
587                 'Get it from: <a href="http://www.object-craft.com.au/projects/csv/">http://www.object-craft.com.au/projects/csv/'))
588             return
590         # do the edit
591         if self.form.has_key('rows'):
592             rows = self.form['rows'].value.splitlines()
593             p = csv.parser()
594             found = {}
595             line = 0
596             for row in rows:
597                 line += 1
598                 values = p.parse(row)
599                 # not a complete row, keep going
600                 if not values: continue
602                 # extract the nodeid
603                 nodeid, values = values[0], values[1:]
604                 found[nodeid] = 1
606                 # confirm correct weight
607                 if len(idlessprops) != len(values):
608                     w(_('Not enough values on line %(line)s'%{'line':line}))
609                     return
611                 # extract the new values
612                 d = {}
613                 for name, value in zip(idlessprops, values):
614                     value = value.strip()
615                     # only add the property if it has a value
616                     if value:
617                         # if it's a multilink, split it
618                         if isinstance(cl.properties[name], hyperdb.Multilink):
619                             value = value.split(':')
620                         d[name] = value
622                 # perform the edit
623                 if cl.hasnode(nodeid):
624                     # edit existing
625                     cl.set(nodeid, **d)
626                 else:
627                     # new node
628                     found[cl.create(**d)] = 1
630             # retire the removed entries
631             for nodeid in cl.list():
632                 if not found.has_key(nodeid):
633                     cl.retire(nodeid)
635         w(_('''<p class="form-help">You may edit the contents of the
636         "%(classname)s" class using this form. Commas, newlines and double
637         quotes (") must be handled delicately. You may include commas and
638         newlines by enclosing the values in double-quotes ("). Double
639         quotes themselves must be quoted by doubling ("").</p>
640         <p class="form-help">Multilink properties have their multiple
641         values colon (":") separated (... ,"one:two:three", ...)</p>
642         <p class="form-help">Remove entries by deleting their line. Add
643         new entries by appending
644         them to the table - put an X in the id column.</p>''')%{'classname':cn})
646         l = []
647         for name in props:
648             l.append(name)
649         w('<tt>')
650         w(', '.join(l) + '\n')
651         w('</tt>')
653         w('<form onSubmit="return submit_once()" method="POST">')
654         w('<textarea name="rows" cols=80 rows=15>')
655         p = csv.parser()
656         for nodeid in cl.list():
657             l = []
658             for name in props:
659                 value = cl.get(nodeid, name)
660                 if value is None:
661                     l.append('')
662                 elif isinstance(value, type([])):
663                     l.append(cgi.escape(':'.join(map(str, value))))
664                 else:
665                     l.append(cgi.escape(str(cl.get(nodeid, name))))
666             w(p.join(l) + '\n')
668         w(_('</textarea><br><input type="submit" value="Save Changes"></form>'))
670     def classhelp(self):
671         '''Display a table of class info
672         '''
673         w = self.write
674         cn = self.form['classname'].value
675         cl = self.db.classes[cn]
676         props = self.form['properties'].value.split(',')
677         if cl.labelprop(1) in props:
678             sort = [cl.labelprop(1)]
679         else:
680             sort = props[0]
682         w('<table border=1 cellspacing=0 cellpaddin=2>')
683         w('<tr>')
684         for name in props:
685             w('<th align=left>%s</th>'%name)
686         w('</tr>')
687         for nodeid in cl.filter(None, {}, sort, []):
688             w('<tr>')
689             for name in props:
690                 value = cgi.escape(str(cl.get(nodeid, name)))
691                 w('<td align="left" valign="top">%s</td>'%value)
692             w('</tr>')
693         w('</table>')
695     def shownode(self, message=None, num_re=re.compile('^\d+$')):
696         ''' display an item
697         '''
698         cn = self.classname
699         cl = self.db.classes[cn]
700         if self.form.has_key(':multilink'):
701             link = self.form[':multilink'].value
702             designator, linkprop = link.split(':')
703             xtra = ' for <a href="%s">%s</a>' % (designator, designator)
704         else:
705             xtra = ''
707         # possibly perform an edit
708         keys = self.form.keys()
709         # don't try to set properties if the user has just logged in
710         if keys and not self.form.has_key('__login_name'):
711             try:
712                 userid = self.db.user.lookup(self.user)
713                 if not self.db.security.hasPermission('Edit', userid, cn):
714                     message = _('You do not have permission to edit %s' %cn)
715                 else:
716                     props = parsePropsFromForm(self.db, cl, self.form, self.nodeid)
717                     # make changes to the node
718                     self._changenode(props)
719                     # handle linked nodes 
720                     self._post_editnode(self.nodeid)
721                     # and some nice feedback for the user
722                     if props:
723                         message = _('%(changes)s edited ok')%{'changes':
724                             ', '.join(props.keys())}
725                     elif self.form.has_key('__note') and self.form['__note'].value:
726                         message = _('note added')
727                     elif (self.form.has_key('__file') and
728                             self.form['__file'].filename):
729                         message = _('file added')
730                     else:
731                         message = _('nothing changed')
732             except:
733                 self.db.rollback()
734                 s = StringIO.StringIO()
735                 traceback.print_exc(None, s)
736                 message = '<pre>%s</pre>'%cgi.escape(s.getvalue())
738         # now the display
739         id = self.nodeid
740         if cl.getkey():
741             id = cl.get(id, cl.getkey())
742         self.pagehead('%s: %s %s'%(self.classname.capitalize(), id, xtra),
743             message)
745         nodeid = self.nodeid
747         # use the template to display the item
748         item = htmltemplate.ItemTemplate(self, self.instance.TEMPLATES,
749             self.classname)
750         item.render(nodeid)
752         self.pagefoot()
753     showissue = shownode
754     showmsg = shownode
755     searchissue = searchnode
757     def showquery(self):
758         queries = self.db.getclass(self.classname)
759         if self.form.keys():
760             sort = self.index_sort()
761             group = self.index_arg(':group')
762             filter = self.index_arg(':filter')
763             columns = self.index_arg(':columns')
764             filterspec = self.index_filterspec(filter, queries.get(self.nodeid, 'klass'))
765             if self.form.has_key('search_text'):
766                 search_text = self.form['search_text'].value
767                 search_text = urllib.quote(search_text)
768             else:
769                 search_text = ''
770             if self.form.has_key(':pagesize'):
771                 pagesize = int(self.form[':pagesize'].value)
772             else:
773                 pagesize = 50
774             # format a query string
775             qd = {}
776             qd[':sort'] = ','.join(map(urllib.quote, sort))
777             qd[':group'] = ','.join(map(urllib.quote, group))
778             qd[':filter'] = ','.join(map(urllib.quote, filter))
779             qd[':columns'] = ','.join(map(urllib.quote, columns))
780             for k, l in filterspec.items():
781                 qd[urllib.quote(k)] = ','.join(map(urllib.quote, l))
782             url = '&'.join([k+'='+v for k,v in qd.items()])
783             url += '&:pagesize=%s' % pagesize
784             if search_text:
785                 url += '&search_text=%s' % search_text
786             if url != queries.get(self.nodeid, 'url'):
787                 queries.set(self.nodeid, url=url)
788                 message = _('url edited ok')
789             else:
790                 message = _('nothing changed')
791         else:
792             message = None
793         nm = queries.get(self.nodeid, 'name')
794         self.pagehead('%s: %s'%(self.classname.capitalize(), nm), message)
796         # use the template to display the item
797         item = htmltemplate.ItemTemplate(self, self.instance.TEMPLATES,
798             self.classname)
799         item.render(self.nodeid)
800         self.pagefoot()
801         
802     def _changenode(self, props):
803         ''' change the node based on the contents of the form
804         '''
805         cl = self.db.classes[self.classname]
807         # create the message
808         message, files = self._handle_message()
809         if message:
810             props['messages'] = cl.get(self.nodeid, 'messages') + [message]
811         if files:
812             props['files'] = cl.get(self.nodeid, 'files') + files
814         # make the changes
815         cl.set(self.nodeid, **props)
817     def _createnode(self):
818         ''' create a node based on the contents of the form
819         '''
820         cl = self.db.classes[self.classname]
821         props = parsePropsFromForm(self.db, cl, self.form)
823         # check for messages and files
824         message, files = self._handle_message()
825         if message:
826             props['messages'] = [message]
827         if files:
828             props['files'] = files
829         # create the node and return it's id
830         return cl.create(**props)
832     def _handle_message(self):
833         ''' generate an edit message
834         '''
835         # handle file attachments 
836         files = []
837         if self.form.has_key('__file'):
838             file = self.form['__file']
839             if file.filename:
840                 filename = file.filename.split('\\')[-1]
841                 mime_type = mimetypes.guess_type(filename)[0]
842                 if not mime_type:
843                     mime_type = "application/octet-stream"
844                 # create the new file entry
845                 files.append(self.db.file.create(type=mime_type,
846                     name=filename, content=file.file.read()))
848         # we don't want to do a message if none of the following is true...
849         cn = self.classname
850         cl = self.db.classes[self.classname]
851         props = cl.getprops()
852         note = None
853         # in a nutshell, don't do anything if there's no note or there's no
854         # NOSY
855         if self.form.has_key('__note'):
856             note = self.form['__note'].value.strip()
857         if not note:
858             return None, files
859         if not props.has_key('messages'):
860             return None, files
861         if not isinstance(props['messages'], hyperdb.Multilink):
862             return None, files
863         if not props['messages'].classname == 'msg':
864             return None, files
865         if not (self.form.has_key('nosy') or note):
866             return None, files
868         # handle the note
869         if '\n' in note:
870             summary = re.split(r'\n\r?', note)[0]
871         else:
872             summary = note
873         m = ['%s\n'%note]
875         # handle the messageid
876         # TODO: handle inreplyto
877         messageid = "<%s.%s.%s@%s>"%(time.time(), random.random(),
878             self.classname, self.instance.MAIL_DOMAIN)
880         # now create the message, attaching the files
881         content = '\n'.join(m)
882         message_id = self.db.msg.create(author=self.getuid(),
883             recipients=[], date=date.Date('.'), summary=summary,
884             content=content, files=files, messageid=messageid)
886         # update the messages property
887         return message_id, files
889     def _post_editnode(self, nid):
890         '''Do the linking part of the node creation.
892            If a form element has :link or :multilink appended to it, its
893            value specifies a node designator and the property on that node
894            to add _this_ node to as a link or multilink.
896            This is typically used on, eg. the file upload page to indicated
897            which issue to link the file to.
899            TODO: I suspect that this and newfile will go away now that
900            there's the ability to upload a file using the issue __file form
901            element!
902         '''
903         cn = self.classname
904         cl = self.db.classes[cn]
905         # link if necessary
906         keys = self.form.keys()
907         for key in keys:
908             if key == ':multilink':
909                 value = self.form[key].value
910                 if type(value) != type([]): value = [value]
911                 for value in value:
912                     designator, property = value.split(':')
913                     link, nodeid = hyperdb.splitDesignator(designator)
914                     link = self.db.classes[link]
915                     # take a dupe of the list so we're not changing the cache
916                     value = link.get(nodeid, property)[:]
917                     value.append(nid)
918                     link.set(nodeid, **{property: value})
919             elif key == ':link':
920                 value = self.form[key].value
921                 if type(value) != type([]): value = [value]
922                 for value in value:
923                     designator, property = value.split(':')
924                     link, nodeid = hyperdb.splitDesignator(designator)
925                     link = self.db.classes[link]
926                     link.set(nodeid, **{property: nid})
928     def newnode(self, message=None):
929         ''' Add a new node to the database.
930         
931         The form works in two modes: blank form and submission (that is,
932         the submission goes to the same URL). **Eventually this means that
933         the form will have previously entered information in it if
934         submission fails.
936         The new node will be created with the properties specified in the
937         form submission. For multilinks, multiple form entries are handled,
938         as are prop=value,value,value. You can't mix them though.
940         If the new node is to be referenced from somewhere else immediately
941         (ie. the new node is a file that is to be attached to a support
942         issue) then supply one of these arguments in addition to the usual
943         form entries:
944             :link=designator:property
945             :multilink=designator:property
946         ... which means that once the new node is created, the "property"
947         on the node given by "designator" should now reference the new
948         node's id. The node id will be appended to the multilink.
949         '''
950         cn = self.classname
951         userid = self.db.user.lookup(self.user)
952         if not self.db.security.hasPermission('View', userid, cn):
953             raise Unauthorised, _("You do not have permission to access"\
954                         " %(action)s.")%{'action': self.classname}
955         cl = self.db.classes[cn]
956         if self.form.has_key(':multilink'):
957             link = self.form[':multilink'].value
958             designator, linkprop = link.split(':')
959             xtra = ' for <a href="%s">%s</a>' % (designator, designator)
960         else:
961             xtra = ''
963         # possibly perform a create
964         keys = self.form.keys()
965         if [i for i in keys if i[0] != ':']:
966             # no dice if you can't edit!
967             if not self.db.security.hasPermission('Edit', userid, cn):
968                 raise Unauthorised, _("You do not have permission to access"\
969                             " %(action)s.")%{'action': 'new'+self.classname}
970             props = {}
971             try:
972                 nid = self._createnode()
973                 # handle linked nodes 
974                 self._post_editnode(nid)
975                 # and some nice feedback for the user
976                 message = _('%(classname)s created ok')%{'classname': cn}
978                 # render the newly created issue
979                 self.db.commit()
980                 self.nodeid = nid
981                 self.pagehead('%s: %s'%(self.classname.capitalize(), nid),
982                     message)
983                 item = htmltemplate.ItemTemplate(self, self.instance.TEMPLATES, 
984                     self.classname)
985                 item.render(nid)
986                 self.pagefoot()
987                 return
988             except:
989                 self.db.rollback()
990                 s = StringIO.StringIO()
991                 traceback.print_exc(None, s)
992                 message = '<pre>%s</pre>'%cgi.escape(s.getvalue())
993         self.pagehead(_('New %(classname)s %(xtra)s')%{
994                 'classname': self.classname.capitalize(),
995                 'xtra': xtra }, message)
997         # call the template
998         newitem = htmltemplate.NewItemTemplate(self, self.instance.TEMPLATES,
999             self.classname)
1000         newitem.render(self.form)
1002         self.pagefoot()
1003     newissue = newnode
1005     def newuser(self, message=None):
1006         ''' Add a new user to the database.
1008             Don't do any of the message or file handling, just create the node.
1009         '''
1010         userid = self.db.user.lookup(self.user)
1011         if not self.db.security.hasPermission('Edit', userid, 'user'):
1012             raise Unauthorised, _("You do not have permission to access"\
1013                         " %(action)s.")%{'action': 'newuser'}
1015         cn = self.classname
1016         cl = self.db.classes[cn]
1018         # possibly perform a create
1019         keys = self.form.keys()
1020         if [i for i in keys if i[0] != ':']:
1021             try:
1022                 props = parsePropsFromForm(self.db, cl, self.form)
1023                 nid = cl.create(**props)
1024                 # handle linked nodes 
1025                 self._post_editnode(nid)
1026                 # and some nice feedback for the user
1027                 message = _('%(classname)s created ok')%{'classname': cn}
1028             except:
1029                 self.db.rollback()
1030                 s = StringIO.StringIO()
1031                 traceback.print_exc(None, s)
1032                 message = '<pre>%s</pre>'%cgi.escape(s.getvalue())
1033         self.pagehead(_('New %(classname)s')%{'classname':
1034              self.classname.capitalize()}, message)
1036         # call the template
1037         newitem = htmltemplate.NewItemTemplate(self, self.instance.TEMPLATES,
1038             self.classname)
1039         newitem.render(self.form)
1041         self.pagefoot()
1043     def newfile(self, message=None):
1044         ''' Add a new file to the database.
1045         
1046         This form works very much the same way as newnode - it just has a
1047         file upload.
1048         '''
1049         userid = self.db.user.lookup(self.user)
1050         if not self.db.security.hasPermission('Edit', userid, 'file'):
1051             raise Unauthorised, _("You do not have permission to access"\
1052                         " %(action)s.")%{'action': 'newfile'}
1053         cn = self.classname
1054         cl = self.db.classes[cn]
1055         props = parsePropsFromForm(self.db, cl, self.form)
1056         if self.form.has_key(':multilink'):
1057             link = self.form[':multilink'].value
1058             designator, linkprop = link.split(':')
1059             xtra = ' for <a href="%s">%s</a>' % (designator, designator)
1060         else:
1061             xtra = ''
1063         # possibly perform a create
1064         keys = self.form.keys()
1065         if [i for i in keys if i[0] != ':']:
1066             try:
1067                 file = self.form['content']
1068                 mime_type = mimetypes.guess_type(file.filename)[0]
1069                 if not mime_type:
1070                     mime_type = "application/octet-stream"
1071                 # save the file
1072                 props['type'] = mime_type
1073                 props['name'] = file.filename
1074                 props['content'] = file.file.read()
1075                 nid = cl.create(**props)
1076                 # handle linked nodes
1077                 self._post_editnode(nid)
1078                 # and some nice feedback for the user
1079                 message = _('%(classname)s created ok')%{'classname': cn}
1080             except:
1081                 self.db.rollback()
1082                 s = StringIO.StringIO()
1083                 traceback.print_exc(None, s)
1084                 message = '<pre>%s</pre>'%cgi.escape(s.getvalue())
1086         self.pagehead(_('New %(classname)s %(xtra)s')%{
1087                 'classname': self.classname.capitalize(),
1088                 'xtra': xtra }, message)
1089         newitem = htmltemplate.NewItemTemplate(self, self.instance.TEMPLATES,
1090             self.classname)
1091         newitem.render(self.form)
1092         self.pagefoot()
1094     def showuser(self, message=None, num_re=re.compile('^\d+$')):
1095         '''Display a user page for editing. Make sure the user is allowed
1096             to edit this node, and also check for password changes.
1097         '''
1098         user = self.db.user
1100         # get the username of the node being edited
1101         try:
1102             node_user = user.get(self.nodeid, 'username')
1103         except IndexError:
1104             raise NotFound, 'user%s'%self.nodeid
1106         # ok, so we need to be able to edit everything, or be this node's
1107         # user
1108         userid = self.db.user.lookup(self.user)
1109         if (not self.db.security.hasPermission('Edit', userid)
1110                 and self.user != node_user):
1111             raise Unauthorised, _("You do not have permission to access"\
1112                         " %(action)s.")%{'action': self.classname +
1113                         str(self.nodeid)}
1114         
1115         #
1116         # perform any editing
1117         #
1118         keys = self.form.keys()
1119         if keys:
1120             try:
1121                 props = parsePropsFromForm(self.db, user, self.form,
1122                     self.nodeid)
1123                 set_cookie = 0
1124                 if props.has_key('password'):
1125                     password = self.form['password'].value.strip()
1126                     if not password:
1127                         # no password was supplied - don't change it
1128                         del props['password']
1129                     elif self.nodeid == self.getuid():
1130                         # this is the logged-in user's password
1131                         set_cookie = password
1132                 user.set(self.nodeid, **props)
1133                 # and some feedback for the user
1134                 message = _('%(changes)s edited ok')%{'changes':
1135                     ', '.join(props.keys())}
1136             except:
1137                 self.db.rollback()
1138                 s = StringIO.StringIO()
1139                 traceback.print_exc(None, s)
1140                 message = '<pre>%s</pre>'%cgi.escape(s.getvalue())
1141         else:
1142             set_cookie = 0
1144         # fix the cookie if the password has changed
1145         if set_cookie:
1146             self.set_cookie(self.user, set_cookie)
1148         #
1149         # now the display
1150         #
1151         self.pagehead(_('User: %(user)s')%{'user': node_user}, message)
1153         # use the template to display the item
1154         item = htmltemplate.ItemTemplate(self, self.instance.TEMPLATES, 'user')
1155         item.render(self.nodeid)
1156         self.pagefoot()
1158     def showfile(self):
1159         ''' display a file
1160         '''
1161         nodeid = self.nodeid
1162         cl = self.db.classes[self.classname]
1163         try:
1164             mime_type = cl.get(nodeid, 'type')
1165         except IndexError:
1166             raise NotFound, 'file%s'%nodeid
1167         if mime_type == 'message/rfc822':
1168             mime_type = 'text/plain'
1169         self.header(headers={'Content-Type': mime_type})
1170         self.write(cl.get(nodeid, 'content'))
1172     def permission(self):
1173         '''
1174         '''
1176     def classes(self, message=None):
1177         ''' display a list of all the classes in the database
1178         '''
1179         userid = self.db.user.lookup(self.user)
1180         if not self.db.security.hasPermission('Edit', userid):
1181             raise Unauthorised, _("You do not have permission to access"\
1182                         " %(action)s.")%{'action': 'all classes'}
1184         self.pagehead(_('Table of classes'), message)
1185         classnames = self.db.classes.keys()
1186         classnames.sort()
1187         self.write('<table border=0 cellspacing=0 cellpadding=2>\n')
1188         for cn in classnames:
1189             cl = self.db.getclass(cn)
1190             self.write('<tr class="list-header"><th colspan=2 align=left>'
1191                 '<a href="%s">%s</a></th></tr>'%(cn, cn.capitalize()))
1192             for key, value in cl.properties.items():
1193                 if value is None: value = ''
1194                 else: value = str(value)
1195                 self.write('<tr><th align=left>%s</th><td>%s</td></tr>'%(
1196                     key, cgi.escape(value)))
1197         self.write('</table>')
1198         self.pagefoot()
1200     def unauthorised(self, message):
1201         ''' The user is not authorised to do something. If they're
1202             anonymous, throw up a login box. If not, just tell them they
1203             can't do whatever it was they were trying to do.
1205             Bot cases print up the message, which is most likely the
1206             argument to the Unauthorised exception.
1207         '''
1208         self.header(response=403)
1209         if self.desired_action is None or self.desired_action == 'login':
1210             if not message:
1211                 message=_("You do not have permission.")
1212             action = 'index'
1213         else:
1214             if not message:
1215                 message=_("You do not have permission to access"\
1216                     " %(action)s.")%{'action': self.desired_action}
1217             action = self.desired_action
1218         if self.user == 'anonymous':
1219             self.login(action=action, message=message)
1220         else:
1221             self.pagehead(_('Not Authorised'))
1222             self.write('<p class="system-msg">%s</p>'%message)
1223             self.pagefoot()
1225     def login(self, message=None, newuser_form=None, action='index'):
1226         '''Display a login page.
1227         '''
1228         self.pagehead(_('Login to roundup'))
1229         if message:
1230             self.write('<p class="system-msg">%s</p>'%message)
1231         self.write(_('''
1232 <table>
1233 <tr><td colspan=2 class="strong-header">Existing User Login</td></tr>
1234 <form onSubmit="return submit_once()" action="login_action" method=POST>
1235 <input type="hidden" name="__destination_url" value="%(action)s">
1236 <tr><td align=right>Login name: </td>
1237     <td><input name="__login_name"></td></tr>
1238 <tr><td align=right>Password: </td>
1239     <td><input type="password" name="__login_password"></td></tr>
1240 <tr><td></td>
1241     <td><input type="submit" value="Log In"></td></tr>
1242 </form>
1243 ''')%locals())
1244         userid = self.db.user.lookup(self.user)
1245         if not self.db.security.hasPermission('Web Registration', userid):
1246             self.write('</table>')
1247             self.pagefoot()
1248             return
1249         values = {'realname': '', 'organisation': '', 'address': '',
1250             'phone': '', 'username': '', 'password': '', 'confirm': '',
1251             'action': action, 'alternate_addresses': ''}
1252         if newuser_form is not None:
1253             for key in newuser_form.keys():
1254                 values[key] = newuser_form[key].value
1255         self.write(_('''
1256 <p>
1257 <tr><td colspan=2 class="strong-header">New User Registration</td></tr>
1258 <tr><td colspan=2><em>marked items</em> are optional...</td></tr>
1259 <form onSubmit="return submit_once()" action="newuser_action" method=POST>
1260 <input type="hidden" name="__destination_url" value="%(action)s">
1261 <tr><td align=right><em>Name: </em></td>
1262     <td><input name="realname" value="%(realname)s" size=40></td></tr>
1263 <tr><td align=right><em>Organisation: </em></td>
1264     <td><input name="organisation" value="%(organisation)s" size=40></td></tr>
1265 <tr><td align=right>E-Mail Address: </td>
1266     <td><input name="address" value="%(address)s" size=40></td></tr>
1267 <tr><td align=right><em>Alternate E-mail Addresses: </em></td>
1268     <td><textarea name="alternate_addresses" rows=5 cols=40>%(alternate_addresses)s</textarea></td></tr>
1269 <tr><td align=right><em>Phone: </em></td>
1270     <td><input name="phone" value="%(phone)s"></td></tr>
1271 <tr><td align=right>Preferred Login name: </td>
1272     <td><input name="username" value="%(username)s"></td></tr>
1273 <tr><td align=right>Password: </td>
1274     <td><input type="password" name="password" value="%(password)s"></td></tr>
1275 <tr><td align=right>Password Again: </td>
1276     <td><input type="password" name="confirm" value="%(confirm)s"></td></tr>
1277 <tr><td></td>
1278     <td><input type="submit" value="Register"></td></tr>
1279 </form>
1280 </table>
1281 ''')%values)
1282         self.pagefoot()
1284     def login_action(self, message=None):
1285         '''Attempt to log a user in and set the cookie
1287         returns 0 if a page is generated as a result of this call, and
1288         1 if not (ie. the login is successful
1289         '''
1290         if not self.form.has_key('__login_name'):
1291             self.login(message=_('Username required'))
1292             return 0
1293         self.user = self.form['__login_name'].value
1294         # re-open the database for real, using the user
1295         self.opendb(self.user)
1296         if self.form.has_key('__login_password'):
1297             password = self.form['__login_password'].value
1298         else:
1299             password = ''
1300         # make sure the user exists
1301         try:
1302             uid = self.db.user.lookup(self.user)
1303         except KeyError:
1304             name = self.user
1305             self.make_user_anonymous()
1306             action = self.form['__destination_url'].value
1307             self.login(message=_('No such user "%(name)s"')%locals(),
1308                 action=action)
1309             return 0
1311         # and that the password is correct
1312         pw = self.db.user.get(uid, 'password')
1313         if password != pw:
1314             self.make_user_anonymous()
1315             action = self.form['__destination_url'].value
1316             self.login(message=_('Incorrect password'), action=action)
1317             return 0
1319         self.set_cookie(self.user, password)
1320         return 1
1322     def newuser_action(self, message=None):
1323         '''Attempt to create a new user based on the contents of the form
1324         and then set the cookie.
1326         return 1 on successful login
1327         '''
1328         # make sure we're allowed to register
1329         userid = self.db.user.lookup(self.user)
1330         if not self.db.security.hasPermission('Web Registration', userid):
1331             raise Unauthorised, _("You do not have permission to access"\
1332                         " %(action)s.")%{'action': 'registration'}
1334         # re-open the database as "admin"
1335         if self.user != 'admin':
1336             self.opendb('admin')
1337             
1338         # create the new user
1339         cl = self.db.user
1340         try:
1341             props = parsePropsFromForm(self.db, cl, self.form)
1342             props['roles'] = self.instance.NEW_WEB_USER_ROLES
1343             uid = cl.create(**props)
1344             self.db.commit()
1345         except ValueError, message:
1346             action = self.form['__destination_url'].value
1347             self.login(message, action=action)
1348             return 0
1350         # log the new user in
1351         self.user = cl.get(uid, 'username')
1352         # re-open the database for real, using the user
1353         self.opendb(self.user)
1354         password = cl.get(uid, 'password')
1355         self.set_cookie(self.user, password)
1356         return 1
1358     def set_cookie(self, user, password):
1359         # TODO generate a much, much stronger session key ;)
1360         self.session = binascii.b2a_base64(repr(time.time())).strip()
1362         # clean up the base64
1363         if self.session[-1] == '=':
1364             if self.session[-2] == '=':
1365                 self.session = self.session[:-2]
1366             else:
1367                 self.session = self.session[:-1]
1369         # insert the session in the sessiondb
1370         self.db.sessions.set(self.session, user=user, last_use=time.time())
1372         # and commit immediately
1373         self.db.sessions.commit()
1375         # expire us in a long, long time
1376         expire = Cookie._getdate(86400*365)
1378         # generate the cookie path - make sure it has a trailing '/'
1379         path = '/'.join((self.env['SCRIPT_NAME'], self.env['INSTANCE_NAME'],
1380             ''))
1381         self.header({'Set-Cookie': 'roundup_user=%s; expires=%s; Path=%s;'%(
1382             self.session, expire, path)})
1384     def make_user_anonymous(self):
1385         ''' Make us anonymous
1387             This method used to handle non-existence of the 'anonymous'
1388             user, but that user is mandatory now.
1389         '''
1390         self.db.user.lookup('anonymous')
1391         self.user = 'anonymous'
1393     def logout(self, message=None):
1394         ''' Make us really anonymous - nuke the cookie too
1395         '''
1396         self.make_user_anonymous()
1398         # construct the logout cookie
1399         now = Cookie._getdate()
1400         path = '/'.join((self.env['SCRIPT_NAME'], self.env['INSTANCE_NAME'],
1401             ''))
1402         self.header({'Set-Cookie':
1403             'roundup_user=deleted; Max-Age=0; expires=%s; Path=%s;'%(now,
1404             path)})
1405         self.login()
1407     def opendb(self, user):
1408         ''' Open the database - but include the definition of the sessions db.
1409         '''
1410         # open the db
1411         self.db = self.instance.open(user)
1413     def main(self):
1414         ''' Wrap the request and handle unauthorised requests
1415         '''
1416         self.desired_action = None
1417         try:
1418             self.main_action()
1419         except Unauthorised, message:
1420             self.unauthorised(message)
1422     def main_action(self):
1423         '''Wrap the database accesses so we can close the database cleanly
1424         '''
1425         # determine the uid to use
1426         self.opendb('admin')
1428         # make sure we have the session Class
1429         sessions = self.db.sessions
1431         # age sessions, remove when they haven't been used for a week
1432         # TODO: this shouldn't be done every access
1433         week = 60*60*24*7
1434         now = time.time()
1435         for sessid in sessions.list():
1436             interval = now - sessions.get(sessid, 'last_use')
1437             if interval > week:
1438                 sessions.destroy(sessid)
1440         # look up the user session cookie
1441         cookie = Cookie.Cookie(self.env.get('HTTP_COOKIE', ''))
1442         user = 'anonymous'
1444         if (cookie.has_key('roundup_user') and
1445                 cookie['roundup_user'].value != 'deleted'):
1447             # get the session key from the cookie
1448             self.session = cookie['roundup_user'].value
1449             # get the user from the session
1450             try:
1451                 # update the lifetime datestamp
1452                 sessions.set(self.session, last_use=time.time())
1453                 sessions.commit()
1454                 user = sessions.get(self.session, 'user')
1455             except KeyError:
1456                 user = 'anonymous'
1458         # sanity check on the user still being valid
1459         try:
1460             self.db.user.lookup(user)
1461         except (KeyError, TypeError):
1462             user = 'anonymous'
1464         # make sure the anonymous user is valid if we're using it
1465         if user == 'anonymous':
1466             self.make_user_anonymous()
1467         else:
1468             self.user = user
1470         # now figure which function to call
1471         path = self.split_path
1473         # default action to index if the path has no information in it
1474         if not path or path[0] in ('', 'index'):
1475             action = 'index'
1476         else:
1477             action = path[0]
1478         self.desired_action = action
1480         # Everthing ignores path[1:]
1481         #  - The file download link generator actually relies on this - it
1482         #    appends the name of the file to the URL so the download file name
1483         #    is correct, but doesn't actually use it.
1485         # everyone is allowed to try to log in
1486         if action == 'login_action':
1487             # try to login
1488             if not self.login_action():
1489                 return
1490             # figure the resulting page
1491             action = self.form['__destination_url'].value
1492             if not action:
1493                 action = 'index'
1494             self.do_action(action)
1495             return
1497         # allow anonymous people to register
1498         if action == 'newuser_action':
1499             # try to add the user
1500             if not self.newuser_action():
1501                 return
1502             # figure the resulting page
1503             action = self.form['__destination_url'].value
1504             if not action:
1505                 action = 'index'
1507         # re-open the database for real, using the user
1508         self.opendb(self.user)
1510         # just a regular action
1511         self.do_action(action)
1513         # commit all changes to the database
1514         self.db.commit()
1516     def do_action(self, action, dre=re.compile(r'([^\d]+)(\d+)'),
1517             nre=re.compile(r'new(\w+)'), sre=re.compile(r'search(\w+)')):
1518         '''Figure the user's action and do it.
1519         '''
1520         # here be the "normal" functionality
1521         if action == 'index':
1522             self.index()
1523             return
1524         if action == 'list_classes':
1525             self.classes()
1526             return
1527         if action == 'classhelp':
1528             self.classhelp()
1529             return
1530         if action == 'login':
1531             self.login()
1532             return
1533         if action == 'logout':
1534             self.logout()
1535             return
1537         # see if we're to display an existing node
1538         m = dre.match(action)
1539         if m:
1540             self.classname = m.group(1)
1541             self.nodeid = m.group(2)
1542             try:
1543                 cl = self.db.classes[self.classname]
1544             except KeyError:
1545                 raise NotFound, self.classname
1546             try:
1547                 cl.get(self.nodeid, 'id')
1548             except IndexError:
1549                 raise NotFound, self.nodeid
1550             try:
1551                 func = getattr(self, 'show%s'%self.classname)
1552             except AttributeError:
1553                 raise NotFound, 'show%s'%self.classname
1554             func()
1555             return
1557         # see if we're to put up the new node page
1558         m = nre.match(action)
1559         if m:
1560             self.classname = m.group(1)
1561             try:
1562                 func = getattr(self, 'new%s'%self.classname)
1563             except AttributeError:
1564                 raise NotFound, 'new%s'%self.classname
1565             func()
1566             return
1568         # see if we're to put up the new node page
1569         m = sre.match(action)
1570         if m:
1571             self.classname = m.group(1)
1572             try:
1573                 func = getattr(self, 'search%s'%self.classname)
1574             except AttributeError:
1575                 raise NotFound
1576             func()
1577             return
1579         # otherwise, display the named class
1580         self.classname = action
1581         try:
1582             self.db.getclass(self.classname)
1583         except KeyError:
1584             raise NotFound, self.classname
1585         self.list()
1588 class ExtendedClient(Client): 
1589     '''Includes pages and page heading information that relate to the
1590        extended schema.
1591     ''' 
1592     showsupport = Client.shownode
1593     showtimelog = Client.shownode
1594     newsupport = Client.newnode
1595     newtimelog = Client.newnode
1596     searchsupport = Client.searchnode
1598     default_index_sort = ['-activity']
1599     default_index_group = ['priority']
1600     default_index_filter = ['status']
1601     default_index_columns = ['activity','status','title','assignedto']
1602     default_index_filterspec = {'status': ['1', '2', '3', '4', '5', '6', '7']}
1603     default_pagesize = '50'
1605 def parsePropsFromForm(db, cl, form, nodeid=0, num_re=re.compile('^\d+$')):
1606     '''Pull properties for the given class out of the form.
1607     '''
1608     props = {}
1609     keys = form.keys()
1610     for key in keys:
1611         if not cl.properties.has_key(key):
1612             continue
1613         proptype = cl.properties[key]
1614         if isinstance(proptype, hyperdb.String):
1615             value = form[key].value.strip()
1616         elif isinstance(proptype, hyperdb.Password):
1617             value = password.Password(form[key].value.strip())
1618         elif isinstance(proptype, hyperdb.Date):
1619             value = form[key].value.strip()
1620             if value:
1621                 value = date.Date(form[key].value.strip())
1622             else:
1623                 value = None
1624         elif isinstance(proptype, hyperdb.Interval):
1625             value = form[key].value.strip()
1626             if value:
1627                 value = date.Interval(form[key].value.strip())
1628             else:
1629                 value = None
1630         elif isinstance(proptype, hyperdb.Link):
1631             value = form[key].value.strip()
1632             # see if it's the "no selection" choice
1633             if value == '-1':
1634                 value = None
1635             else:
1636                 # handle key values
1637                 link = cl.properties[key].classname
1638                 if not num_re.match(value):
1639                     try:
1640                         value = db.classes[link].lookup(value)
1641                     except KeyError:
1642                         raise ValueError, _('property "%(propname)s": '
1643                             '%(value)s not a %(classname)s')%{'propname':key, 
1644                             'value': value, 'classname': link}
1645         elif isinstance(proptype, hyperdb.Multilink):
1646             value = form[key]
1647             if hasattr(value, 'value'):
1648                 # Quite likely to be a FormItem instance
1649                 value = value.value
1650             if not isinstance(value, type([])):
1651                 value = [i.strip() for i in value.split(',')]
1652             else:
1653                 value = [i.strip() for i in value]
1654             link = cl.properties[key].classname
1655             l = []
1656             for entry in map(str, value):
1657                 if entry == '': continue
1658                 if not num_re.match(entry):
1659                     try:
1660                         entry = db.classes[link].lookup(entry)
1661                     except KeyError:
1662                         raise ValueError, _('property "%(propname)s": '
1663                             '"%(value)s" not an entry of %(classname)s')%{
1664                             'propname':key, 'value': entry, 'classname': link}
1665                 l.append(entry)
1666             l.sort()
1667             value = l
1668         elif isinstance(proptype, hyperdb.Boolean):
1669             value = form[key].value.strip()
1670             props[key] = value = value.lower() in ('yes', 'true', 'on', '1')
1671         elif isinstance(proptype, hyperdb.Number):
1672             value = form[key].value.strip()
1673             props[key] = value = int(value)
1675         # get the old value
1676         if nodeid:
1677             try:
1678                 existing = cl.get(nodeid, key)
1679             except KeyError:
1680                 # this might be a new property for which there is no existing
1681                 # value
1682                 if not cl.properties.has_key(key): raise
1684             # if changed, set it
1685             if value != existing:
1686                 props[key] = value
1687         else:
1688             props[key] = value
1689     return props
1692 # $Log: not supported by cvs2svn $
1693 # Revision 1.153  2002/07/31 22:40:50  gmcm
1694 # Fixes to the search form and saving queries.
1695 # Fixes to  sorting in back_metakit.py.
1697 # Revision 1.152  2002/07/31 22:04:14  richard
1698 # cleanup
1700 # Revision 1.151  2002/07/30 21:37:43  richard
1701 # oops, thanks Duncan Booth for spotting this one
1703 # Revision 1.150  2002/07/30 20:43:18  gmcm
1704 # Oops, fix the permission check!
1706 # Revision 1.149  2002/07/30 20:04:38  gmcm
1707 # Adapt metakit backend to new security scheme.
1708 # Put some more permission checks in cgi_client.
1710 # Revision 1.148  2002/07/30 16:09:11  gmcm
1711 # Simple optimization.
1713 # Revision 1.147  2002/07/30 08:22:38  richard
1714 # Session storage in the hyperdb was horribly, horribly inefficient. We use
1715 # a simple anydbm wrapper now - which could be overridden by the metakit
1716 # backend or RDB backend if necessary.
1717 # Much, much better.
1719 # Revision 1.146  2002/07/30 05:27:30  richard
1720 # nicer error messages, and a bugfix
1722 # Revision 1.145  2002/07/26 08:26:59  richard
1723 # Very close now. The cgi and mailgw now use the new security API. The two
1724 # templates have been migrated to that setup. Lots of unit tests. Still some
1725 # issue in the web form for editing Roles assigned to users.
1727 # Revision 1.144  2002/07/25 07:14:05  richard
1728 # Bugger it. Here's the current shape of the new security implementation.
1729 # Still to do:
1730 #  . call the security funcs from cgi and mailgw
1731 #  . change shipped templates to include correct initialisation and remove
1732 #    the old config vars
1733 # ... that seems like a lot. The bulk of the work has been done though. Honest :)
1735 # Revision 1.143  2002/07/20 19:29:10  gmcm
1736 # Fixes/improvements to the search form & saved queries.
1738 # Revision 1.142  2002/07/18 11:17:30  gmcm
1739 # Add Number and Boolean types to hyperdb.
1740 # Add conversion cases to web, mail & admin interfaces.
1741 # Add storage/serialization cases to back_anydbm & back_metakit.
1743 # Revision 1.141  2002/07/17 12:39:10  gmcm
1744 # Saving, running & editing queries.
1746 # Revision 1.140  2002/07/14 23:17:15  richard
1747 # cleaned up structure
1749 # Revision 1.139  2002/07/14 06:14:40  richard
1750 # Some more TODOs
1752 # Revision 1.138  2002/07/14 04:03:13  richard
1753 # Implemented a switch to disable journalling for a Class. CGI session
1754 # database now uses it.
1756 # Revision 1.137  2002/07/10 07:00:30  richard
1757 # removed debugging
1759 # Revision 1.136  2002/07/10 06:51:08  richard
1760 # . #576241 ] MultiLink problems in parsePropsFromForm
1762 # Revision 1.135  2002/07/10 00:22:34  richard
1763 #  . switched to using a session-based web login
1765 # Revision 1.134  2002/07/09 04:19:09  richard
1766 # Added reindex command to roundup-admin.
1767 # Fixed reindex on first access.
1768 # Also fixed reindexing of entries that change.
1770 # Revision 1.133  2002/07/08 15:32:05  gmcm
1771 # Pagination of index pages.
1772 # New search form.
1774 # Revision 1.132  2002/07/08 07:26:14  richard
1775 # ehem
1777 # Revision 1.131  2002/07/08 06:53:57  richard
1778 # Not sure why the cgi_client had an indexer argument.
1780 # Revision 1.130  2002/06/27 12:01:53  gmcm
1781 # If the form has a :multilink, put a back href in the pageheader (back to the linked-to node).
1782 # Some minor optimizations (only compile regexes once).
1784 # Revision 1.129  2002/06/20 23:52:11  richard
1785 # Better handling of unauth attempt to edit stuff
1787 # Revision 1.128  2002/06/12 21:28:25  gmcm
1788 # Allow form to set user-properties on a Fileclass.
1789 # Don't assume that a Fileclass is named "files".
1791 # Revision 1.127  2002/06/11 06:38:24  richard
1792 #  . #565996 ] The "Attach a File to this Issue" fails
1794 # Revision 1.126  2002/05/29 01:16:17  richard
1795 # Sorry about this huge checkin! It's fixing a lot of related stuff in one go
1796 # though.
1798 # . #541941 ] changing multilink properties by mail
1799 # . #526730 ] search for messages capability
1800 # . #505180 ] split MailGW.handle_Message
1801 #   - also changed cgi client since it was duplicating the functionality
1802 # . build htmlbase if tests are run using CVS checkout (removed note from
1803 #   installation.txt)
1804 # . don't create an empty message on email issue creation if the email is empty
1806 # Revision 1.125  2002/05/25 07:16:24  rochecompaan
1807 # Merged search_indexing-branch with HEAD
1809 # Revision 1.124  2002/05/24 02:09:24  richard
1810 # Nothing like a live demo to show up the bugs ;)
1812 # Revision 1.123  2002/05/22 05:04:13  richard
1813 # Oops
1815 # Revision 1.122  2002/05/22 04:12:05  richard
1816 #  . applied patch #558876 ] cgi client customization
1817 #    ... with significant additions and modifications ;)
1818 #    - extended handling of ML assignedto to all places it's handled
1819 #    - added more NotFound info
1821 # Revision 1.121  2002/05/21 06:08:10  richard
1822 # Handle migration
1824 # Revision 1.120  2002/05/21 06:05:53  richard
1825 #  . #551483 ] assignedto in Client.make_index_link
1827 # Revision 1.119  2002/05/15 06:21:21  richard
1828 #  . node caching now works, and gives a small boost in performance
1830 # As a part of this, I cleaned up the DEBUG output and implemented TRACE
1831 # output (HYPERDBTRACE='file to trace to') with checkpoints at the start of
1832 # CGI requests. Run roundup with python -O to skip all the DEBUG/TRACE stuff
1833 # (using if __debug__ which is compiled out with -O)
1835 # Revision 1.118  2002/05/12 23:46:33  richard
1836 # ehem, part 2
1838 # Revision 1.117  2002/05/12 23:42:29  richard
1839 # ehem
1841 # Revision 1.116  2002/05/02 08:07:49  richard
1842 # Added the ADD_AUTHOR_TO_NOSY handling to the CGI interface.
1844 # Revision 1.115  2002/04/02 01:56:10  richard
1845 #  . stop sending blank (whitespace-only) notes
1847 # Revision 1.114.2.4  2002/05/02 11:49:18  rochecompaan
1848 # Allow customization of the search filters that should be displayed
1849 # on the search page.
1851 # Revision 1.114.2.3  2002/04/20 13:23:31  rochecompaan
1852 # We now have a separate search page for nodes.  Search links for
1853 # different classes can be customized in instance_config similar to
1854 # index links.
1856 # Revision 1.114.2.2  2002/04/19 19:54:42  rochecompaan
1857 # cgi_client.py
1858 #     removed search link for the time being
1859 #     moved rendering of matches to htmltemplate
1860 # hyperdb.py
1861 #     filtering of nodes on full text search incorporated in filter method
1862 # roundupdb.py
1863 #     added paramater to call of filter method
1864 # roundup_indexer.py
1865 #     added search method to RoundupIndexer class
1867 # Revision 1.114.2.1  2002/04/03 11:55:57  rochecompaan
1868 #  . Added feature #526730 - search for messages capability
1870 # Revision 1.114  2002/03/17 23:06:05  richard
1871 # oops
1873 # Revision 1.113  2002/03/14 23:59:24  richard
1874 #  . #517734 ] web header customisation is obscure
1876 # Revision 1.112  2002/03/12 22:52:26  richard
1877 # more pychecker warnings removed
1879 # Revision 1.111  2002/02/25 04:32:21  richard
1880 # ahem
1882 # Revision 1.110  2002/02/21 07:19:08  richard
1883 # ... and label, width and height control for extra flavour!
1885 # Revision 1.109  2002/02/21 07:08:19  richard
1886 # oops
1888 # Revision 1.108  2002/02/21 07:02:54  richard
1889 # The correct var is "HTTP_HOST"
1891 # Revision 1.107  2002/02/21 06:57:38  richard
1892 #  . Added popup help for classes using the classhelp html template function.
1893 #    - add <display call="classhelp('priority', 'id,name,description')">
1894 #      to an item page, and it generates a link to a popup window which displays
1895 #      the id, name and description for the priority class. The description
1896 #      field won't exist in most installations, but it will be added to the
1897 #      default templates.
1899 # Revision 1.106  2002/02/21 06:23:00  richard
1900 # *** empty log message ***
1902 # Revision 1.105  2002/02/20 05:52:10  richard
1903 # better error handling
1905 # Revision 1.104  2002/02/20 05:45:17  richard
1906 # Use the csv module for generating the form entry so it's correct.
1907 # [also noted the sf.net feature request id in the change log]
1909 # Revision 1.103  2002/02/20 05:05:28  richard
1910 #  . Added simple editing for classes that don't define a templated interface.
1911 #    - access using the admin "class list" interface
1912 #    - limited to admin-only
1913 #    - requires the csv module from object-craft (url given if it's missing)
1915 # Revision 1.102  2002/02/15 07:08:44  richard
1916 #  . Alternate email addresses are now available for users. See the MIGRATION
1917 #    file for info on how to activate the feature.
1919 # Revision 1.101  2002/02/14 23:39:18  richard
1920 # . All forms now have "double-submit" protection when Javascript is enabled
1921 #   on the client-side.
1923 # Revision 1.100  2002/01/16 07:02:57  richard
1924 #  . lots of date/interval related changes:
1925 #    - more relaxed date format for input
1927 # Revision 1.99  2002/01/16 03:02:42  richard
1928 # #503793 ] changing assignedto resets nosy list
1930 # Revision 1.98  2002/01/14 02:20:14  richard
1931 #  . changed all config accesses so they access either the instance or the
1932 #    config attriubute on the db. This means that all config is obtained from
1933 #    instance_config instead of the mish-mash of classes. This will make
1934 #    switching to a ConfigParser setup easier too, I hope.
1936 # At a minimum, this makes migration a _little_ easier (a lot easier in the
1937 # 0.5.0 switch, I hope!)
1939 # Revision 1.97  2002/01/11 23:22:29  richard
1940 #  . #502437 ] rogue reactor and unittest
1941 #    in short, the nosy reactor was modifying the nosy list. That code had
1942 #    been there for a long time, and I suspsect it was there because we
1943 #    weren't generating the nosy list correctly in other places of the code.
1944 #    We're now doing that, so the nosy-modifying code can go away from the
1945 #    nosy reactor.
1947 # Revision 1.96  2002/01/10 05:26:10  richard
1948 # missed a parsePropsFromForm in last update
1950 # Revision 1.95  2002/01/10 03:39:45  richard
1951 #  . fixed some problems with web editing and change detection
1953 # Revision 1.94  2002/01/09 13:54:21  grubert
1954 # _add_assignedto_to_nosy did set nosy to assignedto only, no adding.
1956 # Revision 1.93  2002/01/08 11:57:12  richard
1957 # crying out for real configuration handling... :(
1959 # Revision 1.92  2002/01/08 04:12:05  richard
1960 # Changed message-id format to "<%s.%s.%s%s@%s>" so it complies with RFC822
1962 # Revision 1.91  2002/01/08 04:03:47  richard
1963 # I mucked the intent of the code up.
1965 # Revision 1.90  2002/01/08 03:56:55  richard
1966 # Oops, missed this before the beta:
1967 #  . #495392 ] empty nosy -patch
1969 # Revision 1.89  2002/01/07 20:24:45  richard
1970 # *mutter* stupid cutnpaste
1972 # Revision 1.88  2002/01/02 02:31:38  richard
1973 # Sorry for the huge checkin message - I was only intending to implement #496356
1974 # but I found a number of places where things had been broken by transactions:
1975 #  . modified ROUNDUPDBSENDMAILDEBUG to be SENDMAILDEBUG and hold a filename
1976 #    for _all_ roundup-generated smtp messages to be sent to.
1977 #  . the transaction cache had broken the roundupdb.Class set() reactors
1978 #  . newly-created author users in the mailgw weren't being committed to the db
1980 # Stuff that made it into CHANGES.txt (ie. the stuff I was actually working
1981 # on when I found that stuff :):
1982 #  . #496356 ] Use threading in messages
1983 #  . detectors were being registered multiple times
1984 #  . added tests for mailgw
1985 #  . much better attaching of erroneous messages in the mail gateway
1987 # Revision 1.87  2001/12/23 23:18:49  richard
1988 # We already had an admin-specific section of the web heading, no need to add
1989 # another one :)
1991 # Revision 1.86  2001/12/20 15:43:01  rochecompaan
1992 # Features added:
1993 #  .  Multilink properties are now displayed as comma separated values in
1994 #     a textbox
1995 #  .  The add user link is now only visible to the admin user
1996 #  .  Modified the mail gateway to reject submissions from unknown
1997 #     addresses if ANONYMOUS_ACCESS is denied
1999 # Revision 1.85  2001/12/20 06:13:24  rochecompaan
2000 # Bugs fixed:
2001 #   . Exception handling in hyperdb for strings-that-look-like numbers got
2002 #     lost somewhere
2003 #   . Internet Explorer submits full path for filename - we now strip away
2004 #     the path
2005 # Features added:
2006 #   . Link and multilink properties are now displayed sorted in the cgi
2007 #     interface
2009 # Revision 1.84  2001/12/18 15:30:30  rochecompaan
2010 # Fixed bugs:
2011 #  .  Fixed file creation and retrieval in same transaction in anydbm
2012 #     backend
2013 #  .  Cgi interface now renders new issue after issue creation
2014 #  .  Could not set issue status to resolved through cgi interface
2015 #  .  Mail gateway was changing status back to 'chatting' if status was
2016 #     omitted as an argument
2018 # Revision 1.83  2001/12/15 23:51:01  richard
2019 # Tested the changes and fixed a few problems:
2020 #  . files are now attached to the issue as well as the message
2021 #  . newuser is a real method now since we don't want to do the message/file
2022 #    stuff for it
2023 #  . added some documentation
2024 # The really big changes in the diff are a result of me moving some code
2025 # around to keep like methods together a bit better.
2027 # Revision 1.82  2001/12/15 19:24:39  rochecompaan
2028 #  . Modified cgi interface to change properties only once all changes are
2029 #    collected, files created and messages generated.
2030 #  . Moved generation of change note to nosyreactors.
2031 #  . We now check for changes to "assignedto" to ensure it's added to the
2032 #    nosy list.
2034 # Revision 1.81  2001/12/12 23:55:00  richard
2035 # Fixed some problems with user editing
2037 # Revision 1.80  2001/12/12 23:27:14  richard
2038 # Added a Zope frontend for roundup.
2040 # Revision 1.79  2001/12/10 22:20:01  richard
2041 # Enabled transaction support in the bsddb backend. It uses the anydbm code
2042 # where possible, only replacing methods where the db is opened (it uses the
2043 # btree opener specifically.)
2044 # Also cleaned up some change note generation.
2045 # Made the backends package work with pydoc too.
2047 # Revision 1.78  2001/12/07 05:59:27  rochecompaan
2048 # Fixed small bug that prevented adding issues through the web.
2050 # Revision 1.77  2001/12/06 22:48:29  richard
2051 # files multilink was being nuked in post_edit_node
2053 # Revision 1.76  2001/12/05 14:26:44  rochecompaan
2054 # Removed generation of change note from "sendmessage" in roundupdb.py.
2055 # The change note is now generated when the message is created.
2057 # Revision 1.75  2001/12/04 01:25:08  richard
2058 # Added some rollbacks where we were catching exceptions that would otherwise
2059 # have stopped committing.
2061 # Revision 1.74  2001/12/02 05:06:16  richard
2062 # . We now use weakrefs in the Classes to keep the database reference, so
2063 #   the close() method on the database is no longer needed.
2064 #   I bumped the minimum python requirement up to 2.1 accordingly.
2065 # . #487480 ] roundup-server
2066 # . #487476 ] INSTALL.txt
2068 # I also cleaned up the change message / post-edit stuff in the cgi client.
2069 # There's now a clearly marked "TODO: append the change note" where I believe
2070 # the change note should be added there. The "changes" list will obviously
2071 # have to be modified to be a dict of the changes, or somesuch.
2073 # More testing needed.
2075 # Revision 1.73  2001/12/01 07:17:50  richard
2076 # . We now have basic transaction support! Information is only written to
2077 #   the database when the commit() method is called. Only the anydbm
2078 #   backend is modified in this way - neither of the bsddb backends have been.
2079 #   The mail, admin and cgi interfaces all use commit (except the admin tool
2080 #   doesn't have a commit command, so interactive users can't commit...)
2081 # . Fixed login/registration forwarding the user to the right page (or not,
2082 #   on a failure)
2084 # Revision 1.72  2001/11/30 20:47:58  rochecompaan
2085 # Links in page header are now consistent with default sort order.
2087 # Fixed bugs:
2088 #     - When login failed the list of issues were still rendered.
2089 #     - User was redirected to index page and not to his destination url
2090 #       if his first login attempt failed.
2092 # Revision 1.71  2001/11/30 20:28:10  rochecompaan
2093 # Property changes are now completely traceable, whether changes are
2094 # made through the web or by email
2096 # Revision 1.70  2001/11/30 00:06:29  richard
2097 # Converted roundup/cgi_client.py to use _()
2098 # Added the status file, I18N_PROGRESS.txt
2100 # Revision 1.69  2001/11/29 23:19:51  richard
2101 # Removed the "This issue has been edited through the web" when a valid
2102 # change note is supplied.
2104 # Revision 1.68  2001/11/29 04:57:23  richard
2105 # a little comment
2107 # Revision 1.67  2001/11/28 21:55:35  richard
2108 #  . login_action and newuser_action return values were being ignored
2109 #  . Woohoo! Found that bloody re-login bug that was killing the mail
2110 #    gateway.
2111 #  (also a minor cleanup in hyperdb)
2113 # Revision 1.66  2001/11/27 03:00:50  richard
2114 # couple of bugfixes from latest patch integration
2116 # Revision 1.65  2001/11/26 23:00:53  richard
2117 # This config stuff is getting to be a real mess...
2119 # Revision 1.64  2001/11/26 22:56:35  richard
2120 # typo
2122 # Revision 1.63  2001/11/26 22:55:56  richard
2123 # Feature:
2124 #  . Added INSTANCE_NAME to configuration - used in web and email to identify
2125 #    the instance.
2126 #  . Added EMAIL_SIGNATURE_POSITION to indicate where to place the roundup
2127 #    signature info in e-mails.
2128 #  . Some more flexibility in the mail gateway and more error handling.
2129 #  . Login now takes you to the page you back to the were denied access to.
2131 # Fixed:
2132 #  . Lots of bugs, thanks Roché and others on the devel mailing list!
2134 # Revision 1.62  2001/11/24 00:45:42  jhermann
2135 # typeof() instead of type(): avoid clash with database field(?) "type"
2137 # Fixes this traceback:
2139 # Traceback (most recent call last):
2140 #   File "roundup\cgi_client.py", line 535, in newnode
2141 #     self._post_editnode(nid)
2142 #   File "roundup\cgi_client.py", line 415, in _post_editnode
2143 #     if type(value) != type([]): value = [value]
2144 # UnboundLocalError: local variable 'type' referenced before assignment
2146 # Revision 1.61  2001/11/22 15:46:42  jhermann
2147 # Added module docstrings to all modules.
2149 # Revision 1.60  2001/11/21 22:57:28  jhermann
2150 # Added dummy hooks for I18N and some preliminary (test) markup of
2151 # translatable messages
2153 # Revision 1.59  2001/11/21 03:21:13  richard
2154 # oops
2156 # Revision 1.58  2001/11/21 03:11:28  richard
2157 # Better handling of new properties.
2159 # Revision 1.57  2001/11/15 10:24:27  richard
2160 # handle the case where there is no file attached
2162 # Revision 1.56  2001/11/14 21:35:21  richard
2163 #  . users may attach files to issues (and support in ext) through the web now
2165 # Revision 1.55  2001/11/07 02:34:06  jhermann
2166 # Handling of damaged login cookies
2168 # Revision 1.54  2001/11/07 01:16:12  richard
2169 # Remove the '=' padding from cookie value so quoting isn't an issue.
2171 # Revision 1.53  2001/11/06 23:22:05  jhermann
2172 # More IE fixes: it does not like quotes around cookie values; in the
2173 # hope this does not break anything for other browser; if it does, we
2174 # need to check HTTP_USER_AGENT
2176 # Revision 1.52  2001/11/06 23:11:22  jhermann
2177 # Fixed debug output in page footer; added expiry date to the login cookie
2178 # (expires 1 year in the future) to prevent probs with certain versions
2179 # of IE
2181 # Revision 1.51  2001/11/06 22:00:34  jhermann
2182 # Get debug level from ROUNDUP_DEBUG env var
2184 # Revision 1.50  2001/11/05 23:45:40  richard
2185 # Fixed newuser_action so it sets the cookie with the unencrypted password.
2186 # Also made it present nicer error messages (not tracebacks).
2188 # Revision 1.49  2001/11/04 03:07:12  richard
2189 # Fixed various cookie-related bugs:
2190 #  . bug #477685 ] base64.decodestring breaks
2191 #  . bug #477837 ] lynx does not like the cookie
2192 #  . bug #477892 ] Password edit doesn't fix login cookie
2193 # Also closed a security hole - a logged-in user could edit another user's
2194 # details.
2196 # Revision 1.48  2001/11/03 01:30:18  richard
2197 # Oops. uses pagefoot now.
2199 # Revision 1.47  2001/11/03 01:29:28  richard
2200 # Login page didn't have all close tags.
2202 # Revision 1.46  2001/11/03 01:26:55  richard
2203 # possibly fix truncated base64'ed user:pass
2205 # Revision 1.45  2001/11/01 22:04:37  richard
2206 # Started work on supporting a pop3-fetching server
2207 # Fixed bugs:
2208 #  . bug #477104 ] HTML tag error in roundup-server
2209 #  . bug #477107 ] HTTP header problem
2211 # Revision 1.44  2001/10/28 23:03:08  richard
2212 # Added more useful header to the classic schema.
2214 # Revision 1.43  2001/10/24 00:01:42  richard
2215 # More fixes to lockout logic.
2217 # Revision 1.42  2001/10/23 23:56:03  richard
2218 # HTML typo
2220 # Revision 1.41  2001/10/23 23:52:35  richard
2221 # Fixed lock-out logic, thanks Roch'e for pointing out the problems.
2223 # Revision 1.40  2001/10/23 23:06:39  richard
2224 # Some cleanup.
2226 # Revision 1.39  2001/10/23 01:00:18  richard
2227 # Re-enabled login and registration access after lopping them off via
2228 # disabling access for anonymous users.
2229 # Major re-org of the htmltemplate code, cleaning it up significantly. Fixed
2230 # a couple of bugs while I was there. Probably introduced a couple, but
2231 # things seem to work OK at the moment.
2233 # Revision 1.38  2001/10/22 03:25:01  richard
2234 # Added configuration for:
2235 #  . anonymous user access and registration (deny/allow)
2236 #  . filter "widget" location on index page (top, bottom, both)
2237 # Updated some documentation.
2239 # Revision 1.37  2001/10/21 07:26:35  richard
2240 # feature #473127: Filenames. I modified the file.index and htmltemplate
2241 #  source so that the filename is used in the link and the creation
2242 #  information is displayed.
2244 # Revision 1.36  2001/10/21 04:44:50  richard
2245 # bug #473124: UI inconsistency with Link fields.
2246 #    This also prompted me to fix a fairly long-standing usability issue -
2247 #    that of being able to turn off certain filters.
2249 # Revision 1.35  2001/10/21 00:17:54  richard
2250 # CGI interface view customisation section may now be hidden (patch from
2251 #  Roch'e Compaan.)
2253 # Revision 1.34  2001/10/20 11:58:48  richard
2254 # Catch errors in login - no username or password supplied.
2255 # Fixed editing of password (Password property type) thanks Roch'e Compaan.
2257 # Revision 1.33  2001/10/17 00:18:41  richard
2258 # Manually constructing cookie headers now.
2260 # Revision 1.32  2001/10/16 03:36:21  richard
2261 # CGI interface wasn't handling checkboxes at all.
2263 # Revision 1.31  2001/10/14 10:55:00  richard
2264 # Handle empty strings in HTML template Link function
2266 # Revision 1.30  2001/10/09 07:38:58  richard
2267 # Pushed the base code for the extended schema CGI interface back into the
2268 # code cgi_client module so that future updates will be less painful.
2269 # Also removed a debugging print statement from cgi_client.
2271 # Revision 1.29  2001/10/09 07:25:59  richard
2272 # Added the Password property type. See "pydoc roundup.password" for
2273 # implementation details. Have updated some of the documentation too.
2275 # Revision 1.28  2001/10/08 00:34:31  richard
2276 # Change message was stuffing up for multilinks with no key property.
2278 # Revision 1.27  2001/10/05 02:23:24  richard
2279 #  . roundup-admin create now prompts for property info if none is supplied
2280 #    on the command-line.
2281 #  . hyperdb Class getprops() method may now return only the mutable
2282 #    properties.
2283 #  . Login now uses cookies, which makes it a whole lot more flexible. We can
2284 #    now support anonymous user access (read-only, unless there's an
2285 #    "anonymous" user, in which case write access is permitted). Login
2286 #    handling has been moved into cgi_client.Client.main()
2287 #  . The "extended" schema is now the default in roundup init.
2288 #  . The schemas have had their page headings modified to cope with the new
2289 #    login handling. Existing installations should copy the interfaces.py
2290 #    file from the roundup lib directory to their instance home.
2291 #  . Incorrectly had a Bizar Software copyright on the cgitb.py module from
2292 #    Ping - has been removed.
2293 #  . Fixed a whole bunch of places in the CGI interface where we should have
2294 #    been returning Not Found instead of throwing an exception.
2295 #  . Fixed a deviation from the spec: trying to modify the 'id' property of
2296 #    an item now throws an exception.
2298 # Revision 1.26  2001/09/12 08:31:42  richard
2299 # handle cases where mime type is not guessable
2301 # Revision 1.25  2001/08/29 05:30:49  richard
2302 # change messages weren't being saved when there was no-one on the nosy list.
2304 # Revision 1.24  2001/08/29 04:49:39  richard
2305 # didn't clean up fully after debugging :(
2307 # Revision 1.23  2001/08/29 04:47:18  richard
2308 # Fixed CGI client change messages so they actually include the properties
2309 # changed (again).
2311 # Revision 1.22  2001/08/17 00:08:10  richard
2312 # reverted back to sending messages always regardless of who is doing the web
2313 # edit. change notes weren't being saved. bleah. hackish.
2315 # Revision 1.21  2001/08/15 23:43:18  richard
2316 # Fixed some isFooTypes that I missed.
2317 # Refactored some code in the CGI code.
2319 # Revision 1.20  2001/08/12 06:32:36  richard
2320 # using isinstance(blah, Foo) now instead of isFooType
2322 # Revision 1.19  2001/08/07 00:24:42  richard
2323 # stupid typo
2325 # Revision 1.18  2001/08/07 00:15:51  richard
2326 # Added the copyright/license notice to (nearly) all files at request of
2327 # Bizar Software.
2329 # Revision 1.17  2001/08/02 06:38:17  richard
2330 # Roundupdb now appends "mailing list" information to its messages which
2331 # include the e-mail address and web interface address. Templates may
2332 # override this in their db classes to include specific information (support
2333 # instructions, etc).
2335 # Revision 1.16  2001/08/02 05:55:25  richard
2336 # Web edit messages aren't sent to the person who did the edit any more. No
2337 # message is generated if they are the only person on the nosy list.
2339 # Revision 1.15  2001/08/02 00:34:10  richard
2340 # bleah syntax error
2342 # Revision 1.14  2001/08/02 00:26:16  richard
2343 # Changed the order of the information in the message generated by web edits.
2345 # Revision 1.13  2001/07/30 08:12:17  richard
2346 # Added time logging and file uploading to the templates.
2348 # Revision 1.12  2001/07/30 06:26:31  richard
2349 # Added some documentation on how the newblah works.
2351 # Revision 1.11  2001/07/30 06:17:45  richard
2352 # Features:
2353 #  . Added ability for cgi newblah forms to indicate that the new node
2354 #    should be linked somewhere.
2355 # Fixed:
2356 #  . Fixed the agument handling for the roundup-admin find command.
2357 #  . Fixed handling of summary when no note supplied for newblah. Again.
2358 #  . Fixed detection of no form in htmltemplate Field display.
2360 # Revision 1.10  2001/07/30 02:37:34  richard
2361 # Temporary measure until we have decent schema migration...
2363 # Revision 1.9  2001/07/30 01:25:07  richard
2364 # Default implementation is now "classic" rather than "extended" as one would
2365 # expect.
2367 # Revision 1.8  2001/07/29 08:27:40  richard
2368 # Fixed handling of passed-in values in form elements (ie. during a
2369 # drill-down)
2371 # Revision 1.7  2001/07/29 07:01:39  richard
2372 # Added vim command to all source so that we don't get no steenkin' tabs :)
2374 # Revision 1.6  2001/07/29 04:04:00  richard
2375 # Moved some code around allowing for subclassing to change behaviour.
2377 # Revision 1.5  2001/07/28 08:16:52  richard
2378 # New issue form handles lack of note better now.
2380 # Revision 1.4  2001/07/28 00:34:34  richard
2381 # Fixed some non-string node ids.
2383 # Revision 1.3  2001/07/23 03:56:30  richard
2384 # oops, missed a config removal
2386 # Revision 1.2  2001/07/22 12:09:32  richard
2387 # Final commit of Grande Splite
2389 # Revision 1.1  2001/07/22 11:58:35  richard
2390 # More Grande Splite
2393 # vim: set filetype=python ts=4 sw=4 et si