# # Copyright (c) 2001 Bizar Software Pty Ltd (http://www.bizarsoftware.com.au/) # This module is free software, and you may redistribute it and/or modify # under the same terms as Python, so long as this copyright message and # disclaimer are retained in their original form. # # IN NO EVENT SHALL BIZAR SOFTWARE PTY LTD BE LIABLE TO ANY PARTY FOR # DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING # OUT OF THE USE OF THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # BIZAR SOFTWARE PTY LTD SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" # BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE, # SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. # # $Id: htmltemplate.py,v 1.97 2002-07-09 05:20:09 richard Exp $ __doc__ = """ Template engine. """ import os, re, StringIO, urllib, cgi, errno, types, urllib import hyperdb, date from i18n import _ # This imports the StructureText functionality for the do_stext function # get it from http://dev.zope.org/Members/jim/StructuredTextWiki/NGReleases try: from StructuredText.StructuredText import HTML as StructuredText except ImportError: StructuredText = None class MissingTemplateError(ValueError): '''Error raised when a template file is missing ''' pass class TemplateFunctions: '''Defines the templating functions that are used in the HTML templates of the roundup web interface. ''' def __init__(self): self.form = None self.nodeid = None self.filterspec = None self.globals = {} for key in TemplateFunctions.__dict__.keys(): if key[:3] == 'do_': self.globals[key[3:]] = getattr(self, key) # These are added by the subclass where appropriate self.client = None self.instance = None self.templates = None self.classname = None self.db = None self.cl = None self.properties = None def clear(self): for key in TemplateFunctions.__dict__.keys(): if key[:3] == 'do_': del self.globals[key[3:]] def do_plain(self, property, escape=0, lookup=1): ''' display a String property directly; display a Date property in a specified time zone with an option to omit the time from the date stamp; for a Link or Multilink property, display the key strings of the linked nodes (or the ids if the linked class has no key property) when the lookup argument is true, otherwise just return the linked ids ''' if not self.nodeid and self.form is None: return _('[Field: not called from item]') propclass = self.properties[property] if self.nodeid: # make sure the property is a valid one # TODO: this tests, but we should handle the exception dummy = self.cl.getprops()[property] # get the value for this property try: value = self.cl.get(self.nodeid, property) except KeyError: # a KeyError here means that the node doesn't have a value # for the specified property if isinstance(propclass, hyperdb.Multilink): value = [] else: value = '' else: # TODO: pull the value from the form if isinstance(propclass, hyperdb.Multilink): value = [] else: value = '' if isinstance(propclass, hyperdb.String): if value is None: value = '' else: value = str(value) elif isinstance(propclass, hyperdb.Password): if value is None: value = '' else: value = _('*encrypted*') elif isinstance(propclass, hyperdb.Date): # this gives "2002-01-17.06:54:39", maybe replace the "." by a " ". value = str(value) elif isinstance(propclass, hyperdb.Interval): value = str(value) elif isinstance(propclass, hyperdb.Link): if value: if lookup: linkcl = self.db.classes[propclass.classname] k = linkcl.labelprop(1) value = linkcl.get(value, k) else: value = _('[unselected]') elif isinstance(propclass, hyperdb.Multilink): if lookup: linkcl = self.db.classes[propclass.classname] k = linkcl.labelprop(1) labels = [] for v in value: labels.append(linkcl.get(v, k)) value = ', '.join(labels) else: value = ', '.join(value) else: value = _('Plain: bad propclass "%(propclass)s"')%locals() if escape: value = cgi.escape(value) return value def do_stext(self, property, escape=0): '''Render as structured text using the StructuredText module (see above for details) ''' s = self.do_plain(property, escape=escape) if not StructuredText: return s return StructuredText(s,level=1,header=0) def determine_value(self, property): '''determine the value of a property using the node, form or filterspec ''' propclass = self.properties[property] if self.nodeid: value = self.cl.get(self.nodeid, property, None) if isinstance(propclass, hyperdb.Multilink) and value is None: return [] return value elif self.filterspec is not None: if isinstance(propclass, hyperdb.Multilink): return self.filterspec.get(property, []) else: return self.filterspec.get(property, '') # TODO: pull the value from the form if isinstance(propclass, hyperdb.Multilink): return [] else: return '' def make_sort_function(self, classname): '''Make a sort function for a given class ''' linkcl = self.db.classes[classname] if linkcl.getprops().has_key('order'): sort_on = 'order' else: sort_on = linkcl.labelprop() def sortfunc(a, b, linkcl=linkcl, sort_on=sort_on): return cmp(linkcl.get(a, sort_on), linkcl.get(b, sort_on)) return sortfunc def do_field(self, property, size=None, showid=0): ''' display a property like the plain displayer, but in a text field to be edited Note: if you would prefer an option list style display for link or multilink editing, use menu(). ''' if not self.nodeid and self.form is None and self.filterspec is None: return _('[Field: not called from item]') if size is None: size = 30 propclass = self.properties[property] # get the value value = self.determine_value(property) # now display if (isinstance(propclass, hyperdb.String) or isinstance(propclass, hyperdb.Date) or isinstance(propclass, hyperdb.Interval)): if value is None: value = '' else: value = cgi.escape(str(value)) value = '"'.join(value.split('"')) s = ''%(property, value, size) elif isinstance(propclass, hyperdb.Password): s = ''%(property, size) elif isinstance(propclass, hyperdb.Link): linkcl = self.db.classes[propclass.classname] if linkcl.getprops().has_key('order'): sort_on = 'order' else: sort_on = linkcl.labelprop() options = linkcl.filter(None, {}, [sort_on], []) # TODO: make this a field display, not a menu one! l = ['') s = '\n'.join(l) elif isinstance(propclass, hyperdb.Multilink): sortfunc = self.make_sort_function(propclass.classname) linkcl = self.db.classes[propclass.classname] if value: value.sort(sortfunc) # map the id to the label property if not showid: k = linkcl.labelprop(1) value = [linkcl.get(v, k) for v in value] value = cgi.escape(','.join(value)) s = ''%(property, size, value) else: s = _('Plain: bad propclass "%(propclass)s"')%locals() return s def do_multiline(self, property, rows=5, cols=40): ''' display a string property in a multiline text edit field ''' if not self.nodeid and self.form is None and self.filterspec is None: return _('[Multiline: not called from item]') propclass = self.properties[property] # make sure this is a link property if not isinstance(propclass, hyperdb.String): return _('[Multiline: not a string]') # get the value value = self.determine_value(property) if value is None: value = '' # display return ''%( property, rows, cols, value) def do_menu(self, property, size=None, height=None, showid=0, additional=[]): ''' For a Link/Multilink property, display a menu of the available choices If the additional properties are specified, they will be included in the text of each option in (brackets, with, commas). ''' if not self.nodeid and self.form is None and self.filterspec is None: return _('[Field: not called from item]') propclass = self.properties[property] # make sure this is a link property if not (isinstance(propclass, hyperdb.Link) or isinstance(propclass, hyperdb.Multilink)): return _('[Menu: not a link]') # sort function sortfunc = self.make_sort_function(propclass.classname) # get the value value = self.determine_value(property) # display if isinstance(propclass, hyperdb.Multilink): linkcl = self.db.classes[propclass.classname] if linkcl.getprops().has_key('order'): sort_on = 'order' else: sort_on = linkcl.labelprop() options = linkcl.filter(None, {}, [sort_on], []) height = height or min(len(options), 7) l = ['') return '\n'.join(l) if isinstance(propclass, hyperdb.Link): # force the value to be a single choice if type(value) is types.ListType: value = value[0] linkcl = self.db.classes[propclass.classname] l = ['') return '\n'.join(l) return _('[Menu: not a link]') #XXX deviates from spec def do_link(self, property=None, is_download=0, showid=0): '''For a Link or Multilink property, display the names of the linked nodes, hyperlinked to the item views on those nodes. For other properties, link to this node with the property as the text. If is_download is true, append the property value to the generated URL so that the link may be used as a download link and the downloaded file name is correct. ''' if not self.nodeid and self.form is None: return _('[Link: not called from item]') # get the value value = self.determine_value(property) if not value: return _('[no %(propname)s]')%{'propname':property.capitalize()} propclass = self.properties[property] if isinstance(propclass, hyperdb.Link): linkname = propclass.classname linkcl = self.db.classes[linkname] k = linkcl.labelprop(1) linkvalue = cgi.escape(str(linkcl.get(value, k))) if showid: label = value title = ' title="%s"'%linkvalue # note ... this should be urllib.quote(linkcl.get(value, k)) else: label = linkvalue title = '' if is_download: return '%s'%(linkname, value, linkvalue, title, label) else: return '%s'%(linkname, value, title, label) if isinstance(propclass, hyperdb.Multilink): linkname = propclass.classname linkcl = self.db.classes[linkname] k = linkcl.labelprop(1) l = [] for value in value: linkvalue = cgi.escape(str(linkcl.get(value, k))) if showid: label = value title = ' title="%s"'%linkvalue # note ... this should be urllib.quote(linkcl.get(value, k)) else: label = linkvalue title = '' if is_download: l.append('%s'%(linkname, value, linkvalue, title, label)) else: l.append('%s'%(linkname, value, title, label)) return ', '.join(l) if is_download: return '%s'%(self.classname, self.nodeid, value, value) else: return '%s'%(self.classname, self.nodeid, value) def do_count(self, property, **args): ''' for a Multilink property, display a count of the number of links in the list ''' if not self.nodeid: return _('[Count: not called from item]') propclass = self.properties[property] if not isinstance(propclass, hyperdb.Multilink): return _('[Count: not a Multilink]') # figure the length then... value = self.cl.get(self.nodeid, property) return str(len(value)) # XXX pretty is definitely new ;) def do_reldate(self, property, pretty=0): ''' display a Date property in terms of an interval relative to the current date (e.g. "+ 3w", "- 2d"). with the 'pretty' flag, make it pretty ''' if not self.nodeid and self.form is None: return _('[Reldate: not called from item]') propclass = self.properties[property] if not isinstance(propclass, hyperdb.Date): return _('[Reldate: not a Date]') if self.nodeid: value = self.cl.get(self.nodeid, property) else: return '' if not value: return '' # figure the interval interval = date.Date('.') - value if pretty: if not self.nodeid: return _('now') return interval.pretty() return str(interval) def do_download(self, property, **args): ''' show a Link("file") or Multilink("file") property using links that allow you to download files ''' if not self.nodeid: return _('[Download: not called from item]') return self.do_link(property, is_download=1) def do_checklist(self, property, **args): ''' for a Link or Multilink property, display checkboxes for the available choices to permit filtering ''' propclass = self.properties[property] if (not isinstance(propclass, hyperdb.Link) and not isinstance(propclass, hyperdb.Multilink)): return _('[Checklist: not a link]') # get our current checkbox state if self.nodeid: # get the info from the node - make sure it's a list if isinstance(propclass, hyperdb.Link): value = [self.cl.get(self.nodeid, property)] else: value = self.cl.get(self.nodeid, property) elif self.filterspec is not None: # get the state from the filter specification (always a list) value = self.filterspec.get(property, []) else: # it's a new node, so there's no state value = [] # so we can map to the linked node's "lable" property linkcl = self.db.classes[propclass.classname] l = [] k = linkcl.labelprop(1) for optionid in linkcl.list(): option = cgi.escape(str(linkcl.get(optionid, k))) if optionid in value or option in value: checked = 'checked' else: checked = '' l.append('%s:'%( option, checked, property, option)) # for Links, allow the "unselected" option too if isinstance(propclass, hyperdb.Link): if value is None or '-1' in value: checked = 'checked' else: checked = '' l.append(_('[unselected]:')%(checked, property)) return '\n'.join(l) def do_note(self, rows=5, cols=80): ''' display a "note" field, which is a text area for entering a note to go along with a change. ''' # TODO: pull the value from the form return ''%(rows, cols) # XXX new function def do_list(self, property, reverse=0): ''' list the items specified by property using the standard index for the class ''' propcl = self.properties[property] if not isinstance(propcl, hyperdb.Multilink): return _('[List: not a Multilink]') value = self.determine_value(property) if not value: return '' # sort, possibly revers and then re-stringify value = map(int, value) value.sort() if reverse: value.reverse() value = map(str, value) # render the sub-index into a string fp = StringIO.StringIO() try: write_save = self.client.write self.client.write = fp.write index = IndexTemplate(self.client, self.templates, propcl.classname) index.render(nodeids=value, show_display_form=0) finally: self.client.write = write_save return fp.getvalue() # XXX new function def do_history(self, direction='descending'): ''' list the history of the item If "direction" is 'descending' then the most recent event will be displayed first. If it is 'ascending' then the oldest event will be displayed first. ''' if self.nodeid is None: return _("[History: node doesn't exist]") l = ['
| Date | '), _('User | '), _('Action | '), _('Args | '), '
|---|---|---|---|
| %s | %s | ' '%s | %s |
| Note: | |||
| %s | |||