index 145b3b68b66265c13bb97dc9755f6eb540d7642b..cd4a87194f2705904a0b65e21607d3e79a9ccd3c 100644 (file)
if os.path.isdir(filename): continue
if '.' in filename:
name, extension = filename.split('.')
- self.getTemplate(name, extension)
+ self.get(name, extension)
else:
- self.getTemplate(filename, None)
+ self.get(filename, None)
- def get(self, name, extension):
+ def get(self, name, extension=None):
''' Interface to get a template, possibly loading a compiled template.
"name" and "extension" indicate the template we're after, which in
# default the name to "home"
if name is None:
name = 'home'
+ elif extension is None and '.' in name:
+ # split name
+ name, extension = name.split('.')
# find the source, figure the time it was last modified
if extension:
filename = '%s.%s'%(name, extension)
else:
filename = name
+
src = os.path.join(self.dir, filename)
+ if not os.path.exists(src):
+ filename = filename + '.html'
+ src = os.path.join(self.dir, filename)
+ if not os.path.exists(src):
+ if not extension:
+ raise NoTemplate, 'Template file "%s" doesn\'t exist'%name
+
+ # try for a generic template
+ generic = '_generic.%s'%extension
+ src = os.path.join(self.dir, generic)
+ if not os.path.exists(src):
+ generic = '_generic.%s.html'%extension
+ src = os.path.join(self.dir, generic)
+ if not os.path.exists(src):
+ raise NoTemplate, 'No template file exists for '\
+ 'templating "%s" with template "%s" (neither '\
+ '"%s" nor "%s")'%(name, extension, filename,
+ generic)
+ filename = generic
+
try:
stime = os.stat(src)[os.path.stat.ST_MTIME]
except os.error, error:
if error.errno != errno.ENOENT:
raise
- if not extension:
- raise NoTemplate, 'Template file "%s" doesn\'t exist'%name
-
- # try for a generic template
- generic = '_generic.%s'%extension
- src = os.path.join(self.dir, generic)
- try:
- stime = os.stat(src)[os.path.stat.ST_MTIME]
- except os.error, error:
- if error.errno != errno.ENOENT:
- raise
- # nicer error
- raise NoTemplate, 'No template file exists for templating '\
- '"%s" with template "%s" (neither "%s" nor "%s")'%(name,
- extension, filename, generic)
- filename = generic
if self.templates.has_key(src) and \
stime < self.templates[src].mtime:
# add in the item if there is one
if client.nodeid:
if classname == 'user':
- c['context'] = HTMLUser(client, classname, client.nodeid)
+ c['context'] = HTMLUser(client, classname, client.nodeid,
+ anonymous=1)
else:
- c['context'] = HTMLItem(client, classname, client.nodeid)
+ c['context'] = HTMLItem(client, classname, client.nodeid,
+ anonymous=1)
elif client.db.classes.has_key(classname):
- c['context'] = HTMLClass(client, classname)
+ c['context'] = HTMLClass(client, classname, anonymous=1)
return c
def render(self, client, classname, request, **options):
'''
def __init__(self, client):
self._client = client
+ self._db = client.db
# we want config to be exposed
self.config = client.db.config
- def __getitem__(self, item):
- self._client.db.getclass(item)
- return HTMLClass(self._client, item)
+ def __getitem__(self, item, desre=re.compile(r'(?P<cl>\w+)(?P<id>[-\d]+)')):
+ # check to see if we're actually accessing an item
+ m = desre.match(item)
+ if m:
+ self._client.db.getclass(m.group('cl'))
+ return HTMLItem(self._client, m.group('cl'), m.group('id'))
+ else:
+ self._client.db.getclass(item)
+ return HTMLClass(self._client, item)
def __getattr__(self, attr):
try:
class HTMLClass(HTMLPermissions):
''' Accesses through a class (either through *class* or *db.<classname>*)
'''
- def __init__(self, client, classname):
+ def __init__(self, client, classname, anonymous=0):
self._client = client
self._db = client.db
+ self._anonymous = anonymous
# we want classname to be exposed, but _classname gives a
# consistent API for extending Class/Item
value = []
else:
value = None
- return htmlklass(self._client, '', prop, item, value)
+ return htmlklass(self._client, self._classname, '', prop, item,
+ value, self._anonymous)
# no good
raise KeyError, item
return klass(self._client, self.classname, itemid)
- def properties(self):
+ def properties(self, sort=1):
''' Return HTMLProperty for all of this class' properties.
'''
l = []
else:
value = None
if isinstance(prop, klass):
- l.append(htmlklass(self._client, '', prop, name, value))
+ l.append(htmlklass(self._client, self._classname, '',
+ prop, name, value, self._anonymous))
+ if sort:
+ l.sort(lambda a,b:cmp(a._name, b._name))
return l
def list(self):
''' Return a list of items from this class, filtered and sorted
by the current requested filterspec/filter/sort/group args
'''
+ # XXX allow direct specification of the filterspec etc.
if request is not None:
filterspec = request.filterspec
sort = request.sort
group = request.group
+ else:
+ filterspec = {}
+ sort = (None,None)
+ group = (None,None)
if self.classname == 'user':
klass = HTMLUser
else:
for x in self._klass.filter(None, filterspec, sort, group)]
return l
- def classhelp(self, properties=None, label='list', width='500',
- height='400'):
+ def classhelp(self, properties=None, label='(list)', width='500',
+ height='400', property=''):
''' Pop up a javascript window with class help
This generates a link to a popup window which displays the
You may optionally override the label displayed, the width and
height. The popup window will be resizable and scrollable.
+
+ If the "property" arg is given, it's passed through to the
+ javascript help_window function.
'''
if properties is None:
properties = self._klass.getprops(protected=0).keys()
properties.sort()
properties = ','.join(properties)
- return '<a href="javascript:help_window(\'%s?:template=help&' \
- 'properties=%s\', \'%s\', \'%s\')"><b>(%s)</b></a>'%(
- self.classname, properties, width, height, label)
+ if property:
+ property = '&property=%s'%property
+ return '<a class="classhelp" href="javascript:help_window(\'%s?:'\
+ 'template=help&properties=%s%s\', \'%s\', \'%s\')">%s</a>'%(
+ self.classname, properties, property, width, height, label)
def submit(self, label="Submit New Entry"):
''' Generate a submit button (and action hidden element)
class HTMLItem(HTMLPermissions):
''' Accesses through an *item*
'''
- def __init__(self, client, classname, nodeid):
+ def __init__(self, client, classname, nodeid, anonymous=0):
self._client = client
self._db = client.db
self._classname = classname
self._klass = self._db.getclass(classname)
self._props = self._klass.getprops()
+ # do we prefix the form items with the item's identification?
+ self._anonymous = anonymous
+
def __repr__(self):
return '<HTMLItem(0x%x) %s %s>'%(id(self), self._classname,
self._nodeid)
prop = self._props[item]
# get the value, handling missing values
- value = self._klass.get(self._nodeid, item, None)
+ value = None
+ if int(self._nodeid) > 0:
+ value = self._klass.get(self._nodeid, item, None)
if value is None:
if isinstance(self._props[item], hyperdb.Multilink):
value = []
# look up the correct HTMLProperty class
for klass, htmlklass in propclasses:
if isinstance(prop, klass):
- return htmlklass(self._client, self._nodeid, prop, item, value)
+ return htmlklass(self._client, self._classname,
+ self._nodeid, prop, item, value, self._anonymous)
raise KeyError, item
os.path.join(self._db.config.TEMPLATES,
classname+'.item'))
- if isinstance(prop, hyperdb.Multilink) and \
- len(args[k]) > 0:
+ if isinstance(prop, hyperdb.Multilink) and args[k]:
ml = []
for linkid in args[k]:
if isinstance(linkid, type(())):
d = date.Date(args[k]).local(timezone)
cell.append('%s: %s'%(k, str(d)))
if current.has_key(k):
- if not current[k] == '(no value)' and current[k]:
- current[k] = date.Date(current[k]).local(timezone)
cell[-1] += ' -> %s' % current[k]
current[k] = str(d)
class HTMLUser(HTMLItem):
''' Accesses through the *user* (a special case of item)
'''
- def __init__(self, client, classname, nodeid):
- HTMLItem.__init__(self, client, 'user', nodeid)
+ def __init__(self, client, classname, nodeid, anonymous=0):
+ HTMLItem.__init__(self, client, 'user', nodeid, anonymous)
self._default_classname = client.classname
# used for security checks
self._security = client.db.security
_marker = []
- def hasPermission(self, role, classname=_marker):
- ''' Determine if the user has the Role.
+ def hasPermission(self, permission, classname=_marker):
+ ''' Determine if the user has the Permission.
The class being tested defaults to the template's class, but may
be overidden for this test by suppling an alternate classname.
'''
if classname is self._marker:
classname = self._default_classname
- return self._security.hasPermission(role, self._nodeid, classname)
+ return self._security.hasPermission(permission, self._nodeid, classname)
def is_edit_ok(self):
''' Is the user allowed to Edit the current class?
A wrapper object which may be stringified for the plain() behaviour.
'''
- def __init__(self, client, nodeid, prop, name, value):
+ def __init__(self, client, classname, nodeid, prop, name, value,
+ anonymous=0):
self._client = client
self._db = client.db
+ self._classname = classname
self._nodeid = nodeid
self._prop = prop
- self._name = name
self._value = value
+ self._anonymous = anonymous
+ self._name = name
+ if not anonymous:
+ self._formname = '%s%s@%s'%(classname, nodeid, name)
+ else:
+ self._formname = name
def __repr__(self):
- return '<HTMLProperty(0x%x) %s %r %r>'%(id(self), self._name, self._prop, self._value)
+ return '<HTMLProperty(0x%x) %s %r %r>'%(id(self), self._formname,
+ self._prop, self._value)
def __str__(self):
return self.plain()
def __cmp__(self, other):
else:
value = cgi.escape(str(self._value))
value = '"'.join(value.split('"'))
- return '<input name="%s" value="%s" size="%s">'%(self._name, value, size)
+ return '<input name="%s" value="%s" size="%s">'%(self._formname, value, size)
def multiline(self, escape=0, rows=5, cols=40):
''' Render a multiline form edit field for the property
value = cgi.escape(str(self._value))
value = '"'.join(value.split('"'))
return '<textarea name="%s" rows="%s" cols="%s">%s</textarea>'%(
- self._name, rows, cols, value)
+ self._formname, rows, cols, value)
def email(self, escape=1):
''' Render the value of the property as an obscured email address
def field(self, size = 30):
''' Render a form edit field for the property.
'''
- return '<input type="password" name="%s" size="%s">'%(self._name, size)
+ return '<input type="password" name="%s" size="%s">'%(self._formname, size)
def confirm(self, size = 30):
''' Render a second form edit field for the property, used for
confirmation that the user typed the password correctly. Generates
- a field with name "name:confirm".
+ a field with name ":confirm:name".
'''
- return '<input type="password" name="%s:confirm" size="%s">'%(
- self._name, size)
+ return '<input type="password" name=":confirm:%s" size="%s">'%(
+ self._formname, size)
class NumberHTMLProperty(HTMLProperty):
def plain(self):
else:
value = cgi.escape(str(self._value))
value = '"'.join(value.split('"'))
- return '<input name="%s" value="%s" size="%s">'%(self._name, value, size)
+ return '<input name="%s" value="%s" size="%s">'%(self._formname, value, size)
+
+ def __int__(self):
+ ''' Return an int of me
+ '''
+ return int(self._value)
+
+ def __float__(self):
+ ''' Return a float of me
+ '''
+ return float(self._value)
+
class BooleanHTMLProperty(HTMLProperty):
def plain(self):
''' Render a form edit field for the property
'''
checked = self._value and "checked" or ""
- s = '<input type="radio" name="%s" value="yes" %s>Yes'%(self._name,
+ s = '<input type="radio" name="%s" value="yes" %s>Yes'%(self._formname,
checked)
if checked:
checked = ""
else:
checked = "checked"
- s += '<input type="radio" name="%s" value="no" %s>No'%(self._name,
+ s += '<input type="radio" name="%s" value="no" %s>No'%(self._formname,
checked)
return s
return ''
return str(self._value.local(self._db.getUserTimezone()))
+ def now(self):
+ ''' Return the current time.
+
+ This is useful for defaulting a new value. Returns a
+ DateHTMLProperty.
+ '''
+ return DateHTMLProperty(self._client, self._nodeid, self._prop,
+ self._formname, date.Date('.'))
+
def field(self, size = 30):
''' Render a form edit field for the property
'''
else:
value = cgi.escape(str(self._value.local(self._db.getUserTimezone())))
value = '"'.join(value.split('"'))
- return '<input name="%s" value="%s" size="%s">'%(self._name, value, size)
+ return '<input name="%s" value="%s" size="%s">'%(self._formname, value, size)
def reldate(self, pretty=1):
''' Render the interval between the date and now.
return interval.pretty()
return str(interval)
- def pretty(self, format='%d %B %Y'):
+ _marker = []
+ def pretty(self, format=_marker):
''' Render the date in a pretty format (eg. month names, spaces).
The format string is a standard python strftime format string.
string, then it'll be stripped from the output. This is handy
for the situatin when a date only specifies a month and a year.
'''
- return self._value.pretty()
+ if format is not self._marker:
+ return self._value.pretty(format)
+ else:
+ return self._value.pretty()
def local(self, offset):
''' Return the date/time as a local (timezone offset) date/time.
'''
return DateHTMLProperty(self._client, self._nodeid, self._prop,
- self._name, self._value.local())
+ self._formname, self._value.local(offset))
class IntervalHTMLProperty(HTMLProperty):
def plain(self):
else:
value = cgi.escape(str(self._value))
value = '"'.join(value.split('"'))
- return '<input name="%s" value="%s" size="%s">'%(self._name, value, size)
+ return '<input name="%s" value="%s" size="%s">'%(self._formname, value, size)
class LinkHTMLProperty(HTMLProperty):
''' Link HTMLProperty
entry identified by the assignedto property on item, and then the
name property of that user)
'''
- def __init__(self, *args):
- HTMLProperty.__init__(self, *args)
+ def __init__(self, *args, **kw):
+ HTMLProperty.__init__(self, *args, **kw)
# if we're representing a form value, then the -1 from the form really
# should be a None
if str(self._value) == '-1':
sort_on = linkcl.labelprop()
options = linkcl.filter(None, {}, ('+', sort_on), (None, None))
# TODO: make this a field display, not a menu one!
- l = ['<select name="%s">'%self._name]
+ l = ['<select name="%s">'%self._formname]
k = linkcl.labelprop(1)
if self._value is None:
s = 'selected '
sortfunc = make_sort_function(self._db, self._prop.classname)
linkcl = self._db.getclass(self._prop.classname)
- l = ['<select name="%s">'%self._name]
+ l = ['<select name="%s">'%self._formname]
k = linkcl.labelprop(1)
s = ''
if value is None:
k = linkcl.labelprop(1)
value = [linkcl.get(v, k) for v in value]
value = cgi.escape(','.join(value))
- return '<input name="%s" size="%s" value="%s">'%(self._name, size, value)
+ return '<input name="%s" size="%s" value="%s">'%(self._formname, size, value)
def menu(self, size=None, height=None, showid=0, additional=[],
**conditions):
sort_on = ('+', linkcl.labelprop())
options = linkcl.filter(None, conditions, sort_on, (None,None))
height = height or min(len(options), 7)
- l = ['<select multiple name="%s" size="%s">'%(self._name, height)]
+ l = ['<select multiple name="%s" size="%s">'%(self._formname, height)]
k = linkcl.labelprop(1)
# make sure we list the current values if they're retired
self.classname = client.classname
self.template = client.template
+ # the special char to use for special vars
+ self.special_char = '@'
+
self._post_init()
def _post_init(self):
'''
# extract the index display information from the form
self.columns = []
- if self.form.has_key(':columns'):
- self.columns = handleListCGIValue(self.form[':columns'])
+ for name in ':columns @columns'.split():
+ if self.form.has_key(name):
+ self.special_char = name[0]
+ self.columns = handleListCGIValue(self.form[name])
+ break
self.show = ShowDict(self.columns)
# sorting
self.sort = (None, None)
- if self.form.has_key(':sort'):
- sort = self.form[':sort'].value
- if sort.startswith('-'):
- self.sort = ('-', sort[1:])
- else:
- self.sort = ('+', sort)
- if self.form.has_key(':sortdir'):
- self.sort = ('-', self.sort[1])
+ for name in ':sort @sort'.split():
+ if self.form.has_key(name):
+ self.special_char = name[0]
+ sort = self.form[name].value
+ if sort.startswith('-'):
+ self.sort = ('-', sort[1:])
+ else:
+ self.sort = ('+', sort)
+ if self.form.has_key(self.special_char+'sortdir'):
+ self.sort = ('-', self.sort[1])
# grouping
self.group = (None, None)
- if self.form.has_key(':group'):
- group = self.form[':group'].value
- if group.startswith('-'):
- self.group = ('-', group[1:])
- else:
- self.group = ('+', group)
- if self.form.has_key(':groupdir'):
- self.group = ('-', self.group[1])
+ for name in ':group @group'.split():
+ if self.form.has_key(name):
+ self.special_char = name[0]
+ group = self.form[name].value
+ if group.startswith('-'):
+ self.group = ('-', group[1:])
+ else:
+ self.group = ('+', group)
+ if self.form.has_key(self.special_char+'groupdir'):
+ self.group = ('-', self.group[1])
# filtering
self.filter = []
- if self.form.has_key(':filter'):
- self.filter = handleListCGIValue(self.form[':filter'])
+ for name in ':filter @filter'.split():
+ if self.form.has_key(name):
+ self.special_char = name[0]
+ self.filter = handleListCGIValue(self.form[name])
+
self.filterspec = {}
db = self.client.db
if self.classname is not None:
props = db.getclass(self.classname).getprops()
for name in self.filter:
- if self.form.has_key(name):
- prop = props[name]
- fv = self.form[name]
- if (isinstance(prop, hyperdb.Link) or
- isinstance(prop, hyperdb.Multilink)):
- self.filterspec[name] = lookupIds(db, prop,
- handleListCGIValue(fv))
+ if not self.form.has_key(name):
+ continue
+ prop = props[name]
+ fv = self.form[name]
+ if (isinstance(prop, hyperdb.Link) or
+ isinstance(prop, hyperdb.Multilink)):
+ self.filterspec[name] = lookupIds(db, prop,
+ handleListCGIValue(fv))
+ else:
+ if isinstance(fv, type([])):
+ self.filterspec[name] = [v.value for v in fv]
else:
self.filterspec[name] = fv.value
# full-text search argument
self.search_text = None
- if self.form.has_key(':search_text'):
- self.search_text = self.form[':search_text'].value
+ for name in ':search_text @search_text'.split():
+ if self.form.has_key(name):
+ self.special_char = name[0]
+ self.search_text = self.form[name].value
# pagination - size and start index
# figure batch args
- if self.form.has_key(':pagesize'):
- self.pagesize = int(self.form[':pagesize'].value)
- else:
- self.pagesize = 50
- if self.form.has_key(':startwith'):
- self.startwith = int(self.form[':startwith'].value)
- else:
- self.startwith = 0
+ self.pagesize = 50
+ for name in ':pagesize @pagesize'.split():
+ if self.form.has_key(name):
+ self.special_char = name[0]
+ self.pagesize = int(self.form[name].value)
+
+ self.startwith = 0
+ for name in ':startwith @startwith'.split():
+ if self.form.has_key(name):
+ self.special_char = name[0]
+ self.startwith = int(self.form[name].value)
def updateFromURL(self, url):
''' Parse the URL for query args, and update my attributes using the
filterspec=1):
''' return the current index args as form elements '''
l = []
+ sc = self.special_char
s = '<input type="hidden" name="%s" value="%s">'
if columns and self.columns:
- l.append(s%(':columns', ','.join(self.columns)))
+ l.append(s%(sc+'columns', ','.join(self.columns)))
if sort and self.sort[1] is not None:
if self.sort[0] == '-':
val = '-'+self.sort[1]
else:
val = self.sort[1]
- l.append(s%(':sort', val))
+ l.append(s%(sc+'sort', val))
if group and self.group[1] is not None:
if self.group[0] == '-':
val = '-'+self.group[1]
else:
val = self.group[1]
- l.append(s%(':group', val))
+ l.append(s%(sc+'group', val))
if filter and self.filter:
- l.append(s%(':filter', ','.join(self.filter)))
+ l.append(s%(sc+'filter', ','.join(self.filter)))
if filterspec:
for k,v in self.filterspec.items():
if type(v) == type([]):
else:
l.append(s%(k, v))
if self.search_text:
- l.append(s%(':search_text', self.search_text))
- l.append(s%(':pagesize', self.pagesize))
- l.append(s%(':startwith', self.startwith))
+ l.append(s%(sc+'search_text', self.search_text))
+ l.append(s%(sc+'pagesize', self.pagesize))
+ l.append(s%(sc+'startwith', self.startwith))
return '\n'.join(l)
def indexargs_url(self, url, args):
- ''' embed the current index args in a URL '''
+ ''' Embed the current index args in a URL
+ '''
+ sc = self.special_char
l = ['%s=%s'%(k,v) for k,v in args.items()]
- if self.columns and not args.has_key(':columns'):
- l.append(':columns=%s'%(','.join(self.columns)))
- if self.sort[1] is not None and not args.has_key(':sort'):
+
+ # pull out the special values (prefixed by @ or :)
+ specials = {}
+ for key in args.keys():
+ if key[0] in '@:':
+ specials[key[1:]] = args[key]
+
+ # ok, now handle the specials we received in the request
+ if self.columns and not specials.has_key('columns'):
+ l.append(sc+'columns=%s'%(','.join(self.columns)))
+ if self.sort[1] is not None and not specials.has_key('sort'):
if self.sort[0] == '-':
val = '-'+self.sort[1]
else:
val = self.sort[1]
- l.append(':sort=%s'%val)
- if self.group[1] is not None and not args.has_key(':group'):
+ l.append(sc+'sort=%s'%val)
+ if self.group[1] is not None and not specials.has_key('group'):
if self.group[0] == '-':
val = '-'+self.group[1]
else:
val = self.group[1]
- l.append(':group=%s'%val)
- if self.filter and not args.has_key(':columns'):
- l.append(':filter=%s'%(','.join(self.filter)))
+ l.append(sc+'group=%s'%val)
+ if self.filter and not specials.has_key('filter'):
+ l.append(sc+'filter=%s'%(','.join(self.filter)))
+ if self.search_text and not specials.has_key('search_text'):
+ l.append(sc+'search_text=%s'%self.search_text)
+ if not specials.has_key('pagesize'):
+ l.append(sc+'pagesize=%s'%self.pagesize)
+ if not specials.has_key('startwith'):
+ l.append(sc+'startwith=%s'%self.startwith)
+
+ # finally, the remainder of the filter args in the request
for k,v in self.filterspec.items():
if not args.has_key(k):
if type(v) == type([]):
l.append('%s=%s'%(k, ','.join(v)))
else:
l.append('%s=%s'%(k, v))
- if self.search_text and not args.has_key(':search_text'):
- l.append(':search_text=%s'%self.search_text)
- if not args.has_key(':pagesize'):
- l.append(':pagesize=%s'%self.pagesize)
- if not args.has_key(':startwith'):
- l.append(':startwith=%s'%self.startwith)
return '%s?%s'%(url, '&'.join(l))
indexargs_href = indexargs_url