Code

Added commentage to the dbinit files to help people with their
[roundup.git] / roundup / htmltemplate.py
index fbb21f5e85accc0a75283202dc40cf9fc9930be8..2f6557a1fdb0abba2b3e4d660048c9cfdc2e923b 100644 (file)
 # BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
 # SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
 # 
-# $Id: htmltemplate.py,v 1.79 2002-02-21 06:57:38 richard Exp $
+# $Id: htmltemplate.py,v 1.89 2002-05-15 06:34:47 richard Exp $
 
 __doc__ = """
 Template engine.
 """
 
-import os, re, StringIO, urllib, cgi, errno, types
+import os, re, StringIO, urllib, cgi, errno, types, urllib
 
-import hyperdb, date, password
+import hyperdb, date
 from i18n import _
 
 # This imports the StructureText functionality for the do_stext function
@@ -34,9 +34,14 @@ 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
@@ -46,6 +51,15 @@ class TemplateFunctions:
             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 do_plain(self, property, escape=0):
         ''' display a String property directly;
 
@@ -61,7 +75,7 @@ class TemplateFunctions:
         if self.nodeid:
             # make sure the property is a valid one
             # TODO: this tests, but we should handle the exception
-            prop_test = self.cl.getprops()[property]
+            dummy = self.cl.getprops()[property]
 
             # get the value for this property
             try:
@@ -96,9 +110,12 @@ class TemplateFunctions:
         elif isinstance(propclass, hyperdb.Multilink):
             linkcl = self.db.classes[propclass.classname]
             k = linkcl.labelprop()
-            value = ', '.join(value)
+            labels = []
+            for v in value:
+                labels.append(linkcl.get(v, k))
+            value = ', '.join(labels)
         else:
-            s = _('Plain: bad propclass "%(propclass)s"')%locals()
+            value = _('Plain: bad propclass "%(propclass)s"')%locals()
         if escape:
             value = cgi.escape(value)
         return value
@@ -206,9 +223,8 @@ class TemplateFunctions:
         elif isinstance(propclass, hyperdb.Multilink):
             sortfunc = self.make_sort_function(propclass.classname)
             linkcl = self.db.classes[propclass.classname]
-            list = linkcl.list()
-            list.sort(sortfunc)
-            l = []
+            if value:
+                value.sort(sortfunc)
             # map the id to the label property
             if not showid:
                 k = linkcl.labelprop()
@@ -270,7 +286,7 @@ class TemplateFunctions:
             for optionid in options:
                 option = linkcl.get(optionid, k)
                 s = ''
-                if optionid in value:
+                if optionid in value or option in value:
                     s = 'selected '
                 if showid:
                     lab = '%s%s: %s'%(propclass.classname, optionid, option)
@@ -299,7 +315,7 @@ class TemplateFunctions:
             for optionid in options:
                 option = linkcl.get(optionid, k)
                 s = ''
-                if optionid == value:
+                if value in [optionid, option]:
                     s = 'selected '
                 if showid:
                     lab = '%s%s: %s'%(propclass.classname, optionid, option)
@@ -314,7 +330,7 @@ class TemplateFunctions:
         return _('[Menu: not a link]')
 
     #XXX deviates from spec
-    def do_link(self, property=None, is_download=0):
+    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
@@ -337,25 +353,39 @@ class TemplateFunctions:
             linkname = propclass.classname
             linkcl = self.db.classes[linkname]
             k = linkcl.labelprop()
-            linkvalue = cgi.escape(linkcl.get(value, k))
+            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 '<a href="%s%s/%s">%s</a>'%(linkname, value,
-                    linkvalue, linkvalue)
+                return '<a href="%s%s/%s"%s>%s</a>'%(linkname, value,
+                    linkvalue, title, label)
             else:
-                return '<a href="%s%s">%s</a>'%(linkname, value, linkvalue)
+                return '<a href="%s%s"%s>%s</a>'%(linkname, value, title, label)
         if isinstance(propclass, hyperdb.Multilink):
             linkname = propclass.classname
             linkcl = self.db.classes[linkname]
             k = linkcl.labelprop()
             l = []
             for value in value:
-                linkvalue = cgi.escape(linkcl.get(value, k))
+                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('<a href="%s%s/%s">%s</a>'%(linkname, value,
-                        linkvalue, linkvalue))
+                    l.append('<a href="%s%s/%s"%s>%s</a>'%(linkname, value,
+                        linkvalue, title, label))
                 else:
-                    l.append('<a href="%s%s">%s</a>'%(linkname, value,
-                        linkvalue))
+                    l.append('<a href="%s%s"%s>%s</a>'%(linkname, value,
+                        title, label))
             return ', '.join(l)
         if is_download:
             return '<a href="%s%s/%s">%s</a>'%(self.classname, self.nodeid,
@@ -400,14 +430,11 @@ class TemplateFunctions:
             return ''
 
         # figure the interval
-        interval = value - date.Date('.')
+        interval = date.Date('.') - value
         if pretty:
             if not self.nodeid:
                 return _('now')
-            pretty = interval.pretty()
-            if pretty is None:
-                pretty = value.pretty()
-            return pretty
+            return interval.pretty()
         return str(interval)
 
     def do_download(self, property, **args):
@@ -447,7 +474,7 @@ class TemplateFunctions:
         l = []
         k = linkcl.labelprop()
         for optionid in linkcl.list():
-            option = cgi.escape(linkcl.get(optionid, k))
+            option = cgi.escape(str(linkcl.get(optionid, k)))
             if optionid in value or option in value:
                 checked = 'checked'
             else:
@@ -538,7 +565,7 @@ class TemplateFunctions:
                     arg_s += '<a href="%s%s">%s%s %s</a>'%(linkcl, linkid,
                         linkcl, linkid, key)
                 else:
-                    arg_s = str(arg)
+                    arg_s = str(args)
 
             elif action == 'unlink' and type(args) == type(()):
                 if len(args) == 3:
@@ -546,7 +573,7 @@ class TemplateFunctions:
                     arg_s += '<a href="%s%s">%s%s %s</a>'%(linkcl, linkid,
                         linkcl, linkid, key)
                 else:
-                    arg_s = str(arg)
+                    arg_s = str(args)
 
             elif type(args) == type({}):
                 cell = []
@@ -564,7 +591,7 @@ class TemplateFunctions:
                             classname = prop.classname
                             try:
                                 linkcl = self.db.classes[classname]
-                            except KeyError, message:
+                            except KeyError:
                                 labelprop = None
                                 comments[classname] = _('''The linked class
                                     %(classname)s no longer exists''')%locals()
@@ -655,15 +682,27 @@ class TemplateFunctions:
         else:
             return _('[Submit: not called from item]')
 
-    def do_classhelp(self, classname, properties):
+    def do_classhelp(self, classname, properties, label='?', width='400',
+            height='400'):
         '''pop up a javascript window with class help
+
+           This generates a link to a popup window which displays the 
+           properties indicated by "properties" of the class named by
+           "classname". The "properties" should be a comma-separated list
+           (eg. 'id,name,description').
+
+           You may optionally override the label displayed, the width and
+           height. The popup window will be resizable and scrollable.
         '''
         return '<a href="javascript:help_window(\'classhelp?classname=%s&' \
-            'properties=%s\')"><b>(?)</b></a>'%(classname, properties)
+            'properties=%s\', \'%s\', \'%s\')"><b>(%s)</b></a>'%(classname,
+            properties, width, height, label)
 #
 #   INDEX TEMPLATES
 #
 class IndexTemplateReplace:
+    '''Regular-expression based parser that turns the template into HTML. 
+    '''
     def __init__(self, globals, locals, props):
         self.globals = globals
         self.locals = locals
@@ -680,16 +719,19 @@ class IndexTemplateReplace:
             if m.group('name') in self.props:
                 text = m.group('text')
                 replace = IndexTemplateReplace(self.globals, {}, self.props)
-                return replace.go(m.group('text'))
+                return replace.go(text)
             else:
                 return ''
         if m.group('display'):
             command = m.group('command')
             return eval(command, self.globals, self.locals)
-        print '*** unhandled match', m.groupdict()
+        return '*** unhandled match: %s'%str(m.groupdict())
 
 class IndexTemplate(TemplateFunctions):
+    '''Templating functionality specifically for index pages
+    '''
     def __init__(self, client, templates, classname):
+        TemplateFunctions.__init__(self)
         self.client = client
         self.instance = client.instance
         self.templates = templates
@@ -700,8 +742,6 @@ class IndexTemplate(TemplateFunctions):
         self.cl = self.db.classes[self.classname]
         self.properties = self.cl.getprops()
 
-        TemplateFunctions.__init__(self)
-
     col_re=re.compile(r'<property\s+name="([^>]+)">')
     def render(self, filterspec={}, filter=[], columns=[], sort=[], group=[],
             show_display_form=1, nodeids=None, show_customization=1):
@@ -926,7 +966,6 @@ class IndexTemplate(TemplateFunctions):
             # Grouping
             w(_('<tr><th width="1%" align=right class="location-bar">Grouping</th>\n'))
             for name in names:
-                prop = self.properties[name]
                 if name not in all_columns:
                     w('<td>&nbsp;</td>')
                     continue
@@ -987,6 +1026,8 @@ class IndexTemplate(TemplateFunctions):
 #   ITEM TEMPLATES
 #
 class ItemTemplateReplace:
+    '''Regular-expression based parser that turns the template into HTML. 
+    '''
     def __init__(self, globals, locals, cl, nodeid):
         self.globals = globals
         self.locals = locals
@@ -1010,11 +1051,14 @@ class ItemTemplateReplace:
         if m.group('display'):
             command = m.group('command')
             return eval(command, self.globals, self.locals)
-        print '*** unhandled match', m.groupdict()
+        return '*** unhandled match: %s'%str(m.groupdict())
 
 
 class ItemTemplate(TemplateFunctions):
+    '''Templating functionality specifically for item (node) display
+    '''
     def __init__(self, client, templates, classname):
+        TemplateFunctions.__init__(self)
         self.client = client
         self.instance = client.instance
         self.templates = templates
@@ -1025,8 +1069,6 @@ class ItemTemplate(TemplateFunctions):
         self.cl = self.db.classes[self.classname]
         self.properties = self.cl.getprops()
 
-        TemplateFunctions.__init__(self)
-
     def render(self, nodeid):
         self.nodeid = nodeid
 
@@ -1047,7 +1089,10 @@ class ItemTemplate(TemplateFunctions):
 
 
 class NewItemTemplate(TemplateFunctions):
+    '''Templating functionality specifically for NEW item (node) display
+    '''
     def __init__(self, client, templates, classname):
+        TemplateFunctions.__init__(self)
         self.client = client
         self.instance = client.instance
         self.templates = templates
@@ -1058,8 +1103,6 @@ class NewItemTemplate(TemplateFunctions):
         self.cl = self.db.classes[self.classname]
         self.properties = self.cl.getprops()
 
-        TemplateFunctions.__init__(self)
-
     def render(self, form):
         self.form = form
         w = self.client.write
@@ -1081,6 +1124,55 @@ class NewItemTemplate(TemplateFunctions):
 
 #
 # $Log: not supported by cvs2svn $
+# Revision 1.88  2002/04/24 08:34:35  rochecompaan
+# Sorting was applied to all nodes of the MultiLink class instead of
+# the nodes that are actually linked to in the "field" template
+# function.  This adds about 20+ seconds in the display of an issue if
+# your database has a 1000 or more issue in it.
+#
+# Revision 1.87  2002/04/03 06:12:46  richard
+# Fix for date properties as labels.
+#
+# Revision 1.86  2002/04/03 05:54:31  richard
+# Fixed serialisation problem by moving the serialisation step out of the
+# hyperdb.Class (get, set) into the hyperdb.Database.
+#
+# Also fixed htmltemplate after the showid changes I made yesterday.
+#
+# Unit tests for all of the above written.
+#
+# Revision 1.85  2002/04/02 01:40:58  richard
+#  . link() htmltemplate function now has a "showid" option for links and
+#    multilinks. When true, it only displays the linked node id as the anchor
+#    text. The link value is displayed as a tooltip using the title anchor
+#    attribute.
+#
+# Revision 1.84  2002/03/29 19:41:48  rochecompaan
+#  . Fixed display of mutlilink properties when using the template
+#    functions, menu and plain.
+#
+# Revision 1.83  2002/02/27 04:14:31  richard
+# Ran it through pychecker, made fixes
+#
+# Revision 1.82  2002/02/21 23:11:45  richard
+#  . fixed some problems in date calculations (calendar.py doesn't handle over-
+#    and under-flow). Also, hour/minute/second intervals may now be more than
+#    99 each.
+#
+# Revision 1.81  2002/02/21 07:21:38  richard
+# docco
+#
+# Revision 1.80  2002/02/21 07:19:08  richard
+# ... and label, width and height control for extra flavour!
+#
+# Revision 1.79  2002/02/21 06:57:38  richard
+#  . Added popup help for classes using the classhelp html template function.
+#    - add <display call="classhelp('priority', 'id,name,description')">
+#      to an item page, and it generates a link to a popup window which displays
+#      the id, name and description for the priority class. The description
+#      field won't exist in most installations, but it will be added to the
+#      default templates.
+#
 # Revision 1.78  2002/02/21 06:23:00  richard
 # *** empty log message ***
 #