Correction crash
[auf_roundup.git] / build / lib / roundup / cgi / templating.py
CommitLineData
c638d827
CR
1from __future__ import nested_scopes
2
3"""Implements the API used in the HTML templating for the web interface.
4"""
5
6todo = """
7- Most methods should have a "default" arg to supply a value
8 when none appears in the hyperdb or request.
9- Multilink property additions: change_note and new_upload
10- Add class.find() too
11- NumberHTMLProperty should support numeric operations
12- LinkHTMLProperty should handle comparisons to strings (cf. linked name)
13- HTMLRequest.default(self, sort, group, filter, columns, **filterspec):
14 '''Set the request's view arguments to the given values when no
15 values are found in the CGI environment.
16 '''
17- have menu() methods accept filtering arguments
18"""
19
20__docformat__ = 'restructuredtext'
21
22
23import sys, cgi, urllib, os, re, os.path, time, errno, mimetypes, csv
24import calendar, textwrap
25
26from roundup import hyperdb, date, support
27from roundup import i18n
28from roundup.i18n import _
29
30try:
31 import cPickle as pickle
32except ImportError:
33 import pickle
34try:
35 import cStringIO as StringIO
36except ImportError:
37 import StringIO
38try:
39 from StructuredText.StructuredText import HTML as StructuredText
40except ImportError:
41 try: # older version
42 import StructuredText
43 except ImportError:
44 StructuredText = None
45try:
46 from docutils.core import publish_parts as ReStructuredText
47except ImportError:
48 ReStructuredText = None
49
50# bring in the templating support
51from roundup.cgi.PageTemplates import PageTemplate, GlobalTranslationService
52from roundup.cgi.PageTemplates.Expressions import getEngine
53from roundup.cgi.TAL import TALInterpreter
54from roundup.cgi import TranslationService, ZTUtils
55
56### i18n services
57# this global translation service is not thread-safe.
58# it is left here for backward compatibility
59# until all Web UI translations are done via client.translator object
60translationService = TranslationService.get_translation()
61GlobalTranslationService.setGlobalTranslationService(translationService)
62
63### templating
64
65class NoTemplate(Exception):
66 pass
67
68class Unauthorised(Exception):
69 def __init__(self, action, klass, translator=None):
70 self.action = action
71 self.klass = klass
72 if translator:
73 self._ = translator.gettext
74 else:
75 self._ = TranslationService.get_translation().gettext
76 def __str__(self):
77 return self._('You are not allowed to %(action)s '
78 'items of class %(class)s') % {
79 'action': self.action, 'class': self.klass}
80
81def find_template(dir, name, view):
82 """ Find a template in the nominated dir
83 """
84 # find the source
85 if view:
86 filename = '%s.%s'%(name, view)
87 else:
88 filename = name
89
90 # try old-style
91 src = os.path.join(dir, filename)
92 if os.path.exists(src):
93 return (src, filename)
94
95 # try with a .html or .xml extension (new-style)
96 for extension in '.html', '.xml':
97 f = filename + extension
98 src = os.path.join(dir, f)
99 if os.path.exists(src):
100 return (src, f)
101
102 # no view == no generic template is possible
103 if not view:
104 raise NoTemplate, 'Template file "%s" doesn\'t exist'%name
105
106 # try for a _generic template
107 generic = '_generic.%s'%view
108 src = os.path.join(dir, generic)
109 if os.path.exists(src):
110 return (src, generic)
111
112 # finally, try _generic.html
113 generic = generic + '.html'
114 src = os.path.join(dir, generic)
115 if os.path.exists(src):
116 return (src, generic)
117
118 raise NoTemplate, 'No template file exists for templating "%s" '\
119 'with template "%s" (neither "%s" nor "%s")'%(name, view,
120 filename, generic)
121
122class Templates:
123 templates = {}
124
125 def __init__(self, dir):
126 self.dir = dir
127
128 def precompileTemplates(self):
129 """ Go through a directory and precompile all the templates therein
130 """
131 for filename in os.listdir(self.dir):
132 # skip subdirs
133 if os.path.isdir(filename):
134 continue
135
136 # skip files without ".html" or ".xml" extension - .css, .js etc.
137 for extension in '.html', '.xml':
138 if filename.endswith(extension):
139 break
140 else:
141 continue
142
143 # remove extension
144 filename = filename[:-len(extension)]
145
146 # load the template
147 if '.' in filename:
148 name, extension = filename.split('.', 1)
149 self.get(name, extension)
150 else:
151 self.get(filename, None)
152
153 def get(self, name, extension=None):
154 """ Interface to get a template, possibly loading a compiled template.
155
156 "name" and "extension" indicate the template we're after, which in
157 most cases will be "name.extension". If "extension" is None, then
158 we look for a template just called "name" with no extension.
159
160 If the file "name.extension" doesn't exist, we look for
161 "_generic.extension" as a fallback.
162 """
163 # default the name to "home"
164 if name is None:
165 name = 'home'
166 elif extension is None and '.' in name:
167 # split name
168 name, extension = name.split('.')
169
170 # find the source
171 src, filename = find_template(self.dir, name, extension)
172
173 # has it changed?
174 try:
175 stime = os.stat(src)[os.path.stat.ST_MTIME]
176 except os.error, error:
177 if error.errno != errno.ENOENT:
178 raise
179
180 if self.templates.has_key(src) and \
181 stime <= self.templates[src].mtime:
182 # compiled template is up to date
183 return self.templates[src]
184
185 # compile the template
186 pt = RoundupPageTemplate()
187 # use pt_edit so we can pass the content_type guess too
188 content_type = mimetypes.guess_type(filename)[0] or 'text/html'
189 pt.pt_edit(open(src).read(), content_type)
190 pt.id = filename
191 pt.mtime = stime
192 # Add it to the cache. We cannot do this until the template
193 # is fully initialized, as we could otherwise have a race
194 # condition when running with multiple threads:
195 #
196 # 1. Thread A notices the template is not in the cache,
197 # adds it, but has not yet set "mtime".
198 #
199 # 2. Thread B notices the template is in the cache, checks
200 # "mtime" (above) and crashes.
201 #
202 # Since Python dictionary access is atomic, as long as we
203 # insert "pt" only after it is fully initialized, we avoid
204 # this race condition. It's possible that two separate
205 # threads will both do the work of initializing the template,
206 # but the risk of wasted work is offset by avoiding a lock.
207 self.templates[src] = pt
208 return pt
209
210 def __getitem__(self, name):
211 name, extension = os.path.splitext(name)
212 if extension:
213 extension = extension[1:]
214 try:
215 return self.get(name, extension)
216 except NoTemplate, message:
217 raise KeyError, message
218
219def context(client, template=None, classname=None, request=None):
220 """Return the rendering context dictionary
221
222 The dictionary includes following symbols:
223
224 *context*
225 this is one of three things:
226
227 1. None - we're viewing a "home" page
228 2. The current class of item being displayed. This is an HTMLClass
229 instance.
230 3. The current item from the database, if we're viewing a specific
231 item, as an HTMLItem instance.
232
233 *request*
234 Includes information about the current request, including:
235
236 - the url
237 - the current index information (``filterspec``, ``filter`` args,
238 ``properties``, etc) parsed out of the form.
239 - methods for easy filterspec link generation
240 - *user*, the current user node as an HTMLItem instance
241 - *form*, the current CGI form information as a FieldStorage
242
243 *config*
244 The current tracker config.
245
246 *db*
247 The current database, used to access arbitrary database items.
248
249 *utils*
250 This is a special class that has its base in the TemplatingUtils
251 class in this file. If the tracker interfaces module defines a
252 TemplatingUtils class then it is mixed in, overriding the methods
253 in the base class.
254
255 *templates*
256 Access to all the tracker templates by name.
257 Used mainly in *use-macro* commands.
258
259 *template*
260 Current rendering template.
261
262 *true*
263 Logical True value.
264
265 *false*
266 Logical False value.
267
268 *i18n*
269 Internationalization service, providing string translation
270 methods ``gettext`` and ``ngettext``.
271
272 """
273 # construct the TemplatingUtils class
274 utils = TemplatingUtils
275 if (hasattr(client.instance, 'interfaces') and
276 hasattr(client.instance.interfaces, 'TemplatingUtils')):
277 class utils(client.instance.interfaces.TemplatingUtils, utils):
278 pass
279
280 # if template, classname and/or request are not passed explicitely,
281 # compute form client
282 if template is None:
283 template = client.template
284 if classname is None:
285 classname = client.classname
286 if request is None:
287 request = HTMLRequest(client)
288
289 c = {
290 'context': None,
291 'options': {},
292 'nothing': None,
293 'request': request,
294 'db': HTMLDatabase(client),
295 'config': client.instance.config,
296 'tracker': client.instance,
297 'utils': utils(client),
298 'templates': client.instance.templates,
299 'template': template,
300 'true': 1,
301 'false': 0,
302 'i18n': client.translator
303 }
304 # add in the item if there is one
305 if client.nodeid:
306 c['context'] = HTMLItem(client, classname, client.nodeid,
307 anonymous=1)
308 elif client.db.classes.has_key(classname):
309 c['context'] = HTMLClass(client, classname, anonymous=1)
310 return c
311
312class RoundupPageTemplate(PageTemplate.PageTemplate):
313 """A Roundup-specific PageTemplate.
314
315 Interrogate the client to set up Roundup-specific template variables
316 to be available. See 'context' function for the list of variables.
317
318 """
319
320 # 06-jun-2004 [als] i am not sure if this method is used yet
321 def getContext(self, client, classname, request):
322 return context(client, self, classname, request)
323
324 def render(self, client, classname, request, **options):
325 """Render this Page Template"""
326
327 if not self._v_cooked:
328 self._cook()
329
330 __traceback_supplement__ = (PageTemplate.PageTemplateTracebackSupplement, self)
331
332 if self._v_errors:
333 raise PageTemplate.PTRuntimeError, \
334 'Page Template %s has errors.'%self.id
335
336 # figure the context
337 c = context(client, self, classname, request)
338 c.update({'options': options})
339
340 # and go
341 output = StringIO.StringIO()
342 TALInterpreter.TALInterpreter(self._v_program, self.macros,
343 getEngine().getContext(c), output, tal=1, strictinsert=0)()
344 return output.getvalue()
345
346 def __repr__(self):
347 return '<Roundup PageTemplate %r>'%self.id
348
349class HTMLDatabase:
350 """ Return HTMLClasses for valid class fetches
351 """
352 def __init__(self, client):
353 self._client = client
354 self._ = client._
355 self._db = client.db
356
357 # we want config to be exposed
358 self.config = client.db.config
359
360 def __getitem__(self, item, desre=re.compile(r'(?P<cl>[a-zA-Z_]+)(?P<id>[-\d]+)')):
361 # check to see if we're actually accessing an item
362 m = desre.match(item)
363 if m:
364 cl = m.group('cl')
365 self._client.db.getclass(cl)
366 return HTMLItem(self._client, cl, m.group('id'))
367 else:
368 self._client.db.getclass(item)
369 return HTMLClass(self._client, item)
370
371 def __getattr__(self, attr):
372 try:
373 return self[attr]
374 except KeyError:
375 raise AttributeError, attr
376
377 def classes(self):
378 l = self._client.db.classes.keys()
379 l.sort()
380 m = []
381 for item in l:
382 m.append(HTMLClass(self._client, item))
383 return m
384
385num_re = re.compile('^-?\d+$')
386
387def lookupIds(db, prop, ids, fail_ok=0, num_re=num_re, do_lookup=True):
388 """ "fail_ok" should be specified if we wish to pass through bad values
389 (most likely form values that we wish to represent back to the user)
390 "do_lookup" is there for preventing lookup by key-value (if we
391 know that the value passed *is* an id)
392 """
393 cl = db.getclass(prop.classname)
394 l = []
395 for entry in ids:
396 if do_lookup:
397 try:
398 item = cl.lookup(entry)
399 except (TypeError, KeyError):
400 pass
401 else:
402 l.append(item)
403 continue
404 # if fail_ok, ignore lookup error
405 # otherwise entry must be existing object id rather than key value
406 if fail_ok or num_re.match(entry):
407 l.append(entry)
408 return l
409
410def lookupKeys(linkcl, key, ids, num_re=num_re):
411 """ Look up the "key" values for "ids" list - though some may already
412 be key values, not ids.
413 """
414 l = []
415 for entry in ids:
416 if num_re.match(entry):
417 label = linkcl.get(entry, key)
418 # fall back to designator if label is None
419 if label is None: label = '%s%s'%(linkcl.classname, entry)
420 l.append(label)
421 else:
422 l.append(entry)
423 return l
424
425def _set_input_default_args(dic):
426 # 'text' is the default value anyway --
427 # but for CSS usage it should be present
428 dic.setdefault('type', 'text')
429 # useful e.g for HTML LABELs:
430 if not dic.has_key('id'):
431 try:
432 if dic['text'] in ('radio', 'checkbox'):
433 dic['id'] = '%(name)s-%(value)s' % dic
434 else:
435 dic['id'] = dic['name']
436 except KeyError:
437 pass
438
439def cgi_escape_attrs(**attrs):
440 return ' '.join(['%s="%s"'%(k,cgi.escape(str(v), True))
441 for k,v in attrs.items()])
442
443def input_html4(**attrs):
444 """Generate an 'input' (html4) element with given attributes"""
445 _set_input_default_args(attrs)
446 return '<input %s>'%cgi_escape_attrs(**attrs)
447
448def input_xhtml(**attrs):
449 """Generate an 'input' (xhtml) element with given attributes"""
450 _set_input_default_args(attrs)
451 return '<input %s/>'%cgi_escape_attrs(**attrs)
452
453class HTMLInputMixin:
454 """ requires a _client property """
455 def __init__(self):
456 html_version = 'html4'
457 if hasattr(self._client.instance.config, 'HTML_VERSION'):
458 html_version = self._client.instance.config.HTML_VERSION
459 if html_version == 'xhtml':
460 self.input = input_xhtml
461 else:
462 self.input = input_html4
463 # self._context is used for translations.
464 # will be initialized by the first call to .gettext()
465 self._context = None
466
467 def gettext(self, msgid):
468 """Return the localized translation of msgid"""
469 if self._context is None:
470 self._context = context(self._client)
471 return self._client.translator.translate(domain="roundup",
472 msgid=msgid, context=self._context)
473
474 _ = gettext
475
476class HTMLPermissions:
477
478 def view_check(self):
479 """ Raise the Unauthorised exception if the user's not permitted to
480 view this class.
481 """
482 if not self.is_view_ok():
483 raise Unauthorised("view", self._classname,
484 translator=self._client.translator)
485
486 def edit_check(self):
487 """ Raise the Unauthorised exception if the user's not permitted to
488 edit items of this class.
489 """
490 if not self.is_edit_ok():
491 raise Unauthorised("edit", self._classname,
492 translator=self._client.translator)
493
494 def retire_check(self):
495 """ Raise the Unauthorised exception if the user's not permitted to
496 retire items of this class.
497 """
498 if not self.is_retire_ok():
499 raise Unauthorised("retire", self._classname,
500 translator=self._client.translator)
501
502
503class HTMLClass(HTMLInputMixin, HTMLPermissions):
504 """ Accesses through a class (either through *class* or *db.<classname>*)
505 """
506 def __init__(self, client, classname, anonymous=0):
507 self._client = client
508 self._ = client._
509 self._db = client.db
510 self._anonymous = anonymous
511
512 # we want classname to be exposed, but _classname gives a
513 # consistent API for extending Class/Item
514 self._classname = self.classname = classname
515 self._klass = self._db.getclass(self.classname)
516 self._props = self._klass.getprops()
517
518 HTMLInputMixin.__init__(self)
519
520 def is_edit_ok(self):
521 """ Is the user allowed to Create the current class?
522 """
523 perm = self._db.security.hasPermission
524 return perm('Web Access', self._client.userid) and perm('Create',
525 self._client.userid, self._classname)
526
527 def is_retire_ok(self):
528 """ Is the user allowed to retire items of the current class?
529 """
530 perm = self._db.security.hasPermission
531 return perm('Web Access', self._client.userid) and perm('Retire',
532 self._client.userid, self._classname)
533
534 def is_view_ok(self):
535 """ Is the user allowed to View the current class?
536 """
537 perm = self._db.security.hasPermission
538 return perm('Web Access', self._client.userid) and perm('View',
539 self._client.userid, self._classname)
540
541 def is_only_view_ok(self):
542 """ Is the user only allowed to View (ie. not Create) the current class?
543 """
544 return self.is_view_ok() and not self.is_edit_ok()
545
546 def __repr__(self):
547 return '<HTMLClass(0x%x) %s>'%(id(self), self.classname)
548
549 def __getitem__(self, item):
550 """ return an HTMLProperty instance
551 """
552
553 # we don't exist
554 if item == 'id':
555 return None
556
557 # get the property
558 try:
559 prop = self._props[item]
560 except KeyError:
561 raise KeyError, 'No such property "%s" on %s'%(item, self.classname)
562
563 # look up the correct HTMLProperty class
564 form = self._client.form
565 for klass, htmlklass in propclasses:
566 if not isinstance(prop, klass):
567 continue
568 if isinstance(prop, hyperdb.Multilink):
569 value = []
570 else:
571 value = None
572 return htmlklass(self._client, self._classname, None, prop, item,
573 value, self._anonymous)
574
575 # no good
576 raise KeyError, item
577
578 def __getattr__(self, attr):
579 """ convenience access """
580 try:
581 return self[attr]
582 except KeyError:
583 raise AttributeError, attr
584
585 def designator(self):
586 """ Return this class' designator (classname) """
587 return self._classname
588
589 def getItem(self, itemid, num_re=num_re):
590 """ Get an item of this class by its item id.
591 """
592 # make sure we're looking at an itemid
593 if not isinstance(itemid, type(1)) and not num_re.match(itemid):
594 itemid = self._klass.lookup(itemid)
595
596 return HTMLItem(self._client, self.classname, itemid)
597
598 def properties(self, sort=1):
599 """ Return HTMLProperty for all of this class' properties.
600 """
601 l = []
602 for name, prop in self._props.items():
603 for klass, htmlklass in propclasses:
604 if isinstance(prop, hyperdb.Multilink):
605 value = []
606 else:
607 value = None
608 if isinstance(prop, klass):
609 l.append(htmlklass(self._client, self._classname, '',
610 prop, name, value, self._anonymous))
611 if sort:
612 l.sort(lambda a,b:cmp(a._name, b._name))
613 return l
614
615 def list(self, sort_on=None):
616 """ List all items in this class.
617 """
618 # get the list and sort it nicely
619 l = self._klass.list()
620 sortfunc = make_sort_function(self._db, self._classname, sort_on)
621 l.sort(sortfunc)
622
623 # check perms
624 check = self._client.db.security.hasPermission
625 userid = self._client.userid
626 if not check('Web Access', userid):
627 return []
628
629 l = [HTMLItem(self._client, self._classname, id) for id in l
630 if check('View', userid, self._classname, itemid=id)]
631
632 return l
633
634 def csv(self):
635 """ Return the items of this class as a chunk of CSV text.
636 """
637 props = self.propnames()
638 s = StringIO.StringIO()
639 writer = csv.writer(s)
640 writer.writerow(props)
641 check = self._client.db.security.hasPermission
642 userid = self._client.userid
643 if not check('Web Access', userid):
644 return ''
645 for nodeid in self._klass.list():
646 l = []
647 for name in props:
648 # check permission to view this property on this item
649 if not check('View', userid, itemid=nodeid,
650 classname=self._klass.classname, property=name):
651 raise Unauthorised('view', self._klass.classname,
652 translator=self._client.translator)
653 value = self._klass.get(nodeid, name)
654 if value is None:
655 l.append('')
656 elif isinstance(value, type([])):
657 l.append(':'.join(map(str, value)))
658 else:
659 l.append(str(self._klass.get(nodeid, name)))
660 writer.writerow(l)
661 return s.getvalue()
662
663 def propnames(self):
664 """ Return the list of the names of the properties of this class.
665 """
666 idlessprops = self._klass.getprops(protected=0).keys()
667 idlessprops.sort()
668 return ['id'] + idlessprops
669
670 def filter(self, request=None, filterspec={}, sort=[], group=[]):
671 """ Return a list of items from this class, filtered and sorted
672 by the current requested filterspec/filter/sort/group args
673
674 "request" takes precedence over the other three arguments.
675 """
676 if request is not None:
677 filterspec = request.filterspec
678 sort = request.sort
679 group = request.group
680
681 check = self._db.security.hasPermission
682 userid = self._client.userid
683 if not check('Web Access', userid):
684 return []
685
686 l = [HTMLItem(self._client, self.classname, id)
687 for id in self._klass.filter(None, filterspec, sort, group)
688 if check('View', userid, self.classname, itemid=id)]
689 return l
690
691 def classhelp(self, properties=None, label=''"(list)", width='500',
692 height='400', property='', form='itemSynopsis',
693 pagesize=50, inputtype="checkbox", sort=None, filter=None):
694 """Pop up a javascript window with class help
695
696 This generates a link to a popup window which displays the
697 properties indicated by "properties" of the class named by
698 "classname". The "properties" should be a comma-separated list
699 (eg. 'id,name,description'). Properties defaults to all the
700 properties of a class (excluding id, creator, created and
701 activity).
702
703 You may optionally override the label displayed, the width,
704 the height, the number of items per page and the field on which
705 the list is sorted (defaults to username if in the displayed
706 properties).
707
708 With the "filter" arg it is possible to specify a filter for
709 which items are supposed to be displayed. It has to be of
710 the format "<field>=<values>;<field>=<values>;...".
711
712 The popup window will be resizable and scrollable.
713
714 If the "property" arg is given, it's passed through to the
715 javascript help_window function.
716
717 You can use inputtype="radio" to display a radio box instead
718 of the default checkbox (useful for entering Link-properties)
719
720 If the "form" arg is given, it's passed through to the
721 javascript help_window function. - it's the name of the form
722 the "property" belongs to.
723 """
724 if properties is None:
725 properties = self._klass.getprops(protected=0).keys()
726 properties.sort()
727 properties = ','.join(properties)
728 if sort is None:
729 if 'username' in properties.split( ',' ):
730 sort = 'username'
731 else:
732 sort = self._klass.orderprop()
733 sort = '&amp;@sort=' + sort
734 if property:
735 property = '&amp;property=%s'%property
736 if form:
737 form = '&amp;form=%s'%form
738 if inputtype:
739 type= '&amp;type=%s'%inputtype
740 if filter:
741 filterprops = filter.split(';')
742 filtervalues = []
743 names = []
744 for x in filterprops:
745 (name, values) = x.split('=')
746 names.append(name)
747 filtervalues.append('&amp;%s=%s' % (name, urllib.quote(values)))
748 filter = '&amp;@filter=%s%s' % (','.join(names), ''.join(filtervalues))
749 else:
750 filter = ''
751 help_url = "%s?@startwith=0&amp;@template=help&amp;"\
752 "properties=%s%s%s%s%s&amp;@pagesize=%s%s" % \
753 (self.classname, properties, property, form, type,
754 sort, pagesize, filter)
755 onclick = "javascript:help_window('%s', '%s', '%s');return false;" % \
756 (help_url, width, height)
757 return '<a class="classhelp" href="%s" onclick="%s">%s</a>' % \
758 (help_url, onclick, self._(label))
759
760 def submit(self, label=''"Submit New Entry", action="new"):
761 """ Generate a submit button (and action hidden element)
762
763 Generate nothing if we're not editable.
764 """
765 if not self.is_edit_ok():
766 return ''
767
768 return self.input(type="hidden", name="@action", value=action) + \
769 '\n' + \
770 self.input(type="submit", name="submit_button", value=self._(label))
771
772 def history(self):
773 if not self.is_view_ok():
774 return self._('[hidden]')
775 return self._('New node - no history')
776
777 def renderWith(self, name, **kwargs):
778 """ Render this class with the given template.
779 """
780 # create a new request and override the specified args
781 req = HTMLRequest(self._client)
782 req.classname = self.classname
783 req.update(kwargs)
784
785 # new template, using the specified classname and request
786 pt = self._client.instance.templates.get(self.classname, name)
787
788 # use our fabricated request
789 args = {
790 'ok_message': self._client.ok_message,
791 'error_message': self._client.error_message
792 }
793 return pt.render(self._client, self.classname, req, **args)
794
795class _HTMLItem(HTMLInputMixin, HTMLPermissions):
796 """ Accesses through an *item*
797 """
798 def __init__(self, client, classname, nodeid, anonymous=0):
799 self._client = client
800 self._db = client.db
801 self._classname = classname
802 self._nodeid = nodeid
803 self._klass = self._db.getclass(classname)
804 self._props = self._klass.getprops()
805
806 # do we prefix the form items with the item's identification?
807 self._anonymous = anonymous
808
809 HTMLInputMixin.__init__(self)
810
811 def is_edit_ok(self):
812 """ Is the user allowed to Edit this item?
813 """
814 perm = self._db.security.hasPermission
815 return perm('Web Access', self._client.userid) and perm('Edit',
816 self._client.userid, self._classname, itemid=self._nodeid)
817
818 def is_retire_ok(self):
819 """ Is the user allowed to Reture this item?
820 """
821 perm = self._db.security.hasPermission
822 return perm('Web Access', self._client.userid) and perm('Retire',
823 self._client.userid, self._classname, itemid=self._nodeid)
824
825 def is_view_ok(self):
826 """ Is the user allowed to View this item?
827 """
828 perm = self._db.security.hasPermission
829 if perm('Web Access', self._client.userid) and perm('View',
830 self._client.userid, self._classname, itemid=self._nodeid):
831 return 1
832 return self.is_edit_ok()
833
834 def is_only_view_ok(self):
835 """ Is the user only allowed to View (ie. not Edit) this item?
836 """
837 return self.is_view_ok() and not self.is_edit_ok()
838
839 def __repr__(self):
840 return '<HTMLItem(0x%x) %s %s>'%(id(self), self._classname,
841 self._nodeid)
842
843 def __getitem__(self, item):
844 """ return an HTMLProperty instance
845 this now can handle transitive lookups where item is of the
846 form x.y.z
847 """
848 if item == 'id':
849 return self._nodeid
850
851 items = item.split('.', 1)
852 has_rest = len(items) > 1
853
854 # get the property
855 prop = self._props[items[0]]
856
857 if has_rest and not isinstance(prop, (hyperdb.Link, hyperdb.Multilink)):
858 raise KeyError, item
859
860 # get the value, handling missing values
861 value = None
862 if int(self._nodeid) > 0:
863 value = self._klass.get(self._nodeid, items[0], None)
864 if value is None:
865 if isinstance(prop, hyperdb.Multilink):
866 value = []
867
868 # look up the correct HTMLProperty class
869 htmlprop = None
870 for klass, htmlklass in propclasses:
871 if isinstance(prop, klass):
872 htmlprop = htmlklass(self._client, self._classname,
873 self._nodeid, prop, items[0], value, self._anonymous)
874 if htmlprop is not None:
875 if has_rest:
876 if isinstance(htmlprop, MultilinkHTMLProperty):
877 return [h[items[1]] for h in htmlprop]
878 return htmlprop[items[1]]
879 return htmlprop
880
881 raise KeyError, item
882
883 def __getattr__(self, attr):
884 """ convenience access to properties """
885 try:
886 return self[attr]
887 except KeyError:
888 raise AttributeError, attr
889
890 def designator(self):
891 """Return this item's designator (classname + id)."""
892 return '%s%s'%(self._classname, self._nodeid)
893
894 def is_retired(self):
895 """Is this item retired?"""
896 return self._klass.is_retired(self._nodeid)
897
898 def submit(self, label=''"Submit Changes", action="edit"):
899 """Generate a submit button.
900
901 Also sneak in the lastactivity and action hidden elements.
902 """
903 return self.input(type="hidden", name="@lastactivity",
904 value=self.activity.local(0)) + '\n' + \
905 self.input(type="hidden", name="@action", value=action) + '\n' + \
906 self.input(type="submit", name="submit_button", value=self._(label))
907
908 def journal(self, direction='descending'):
909 """ Return a list of HTMLJournalEntry instances.
910 """
911 # XXX do this
912 return []
913
914 def history(self, direction='descending', dre=re.compile('^\d+$'),
915 limit=None):
916 if not self.is_view_ok():
917 return self._('[hidden]')
918
919 # pre-load the history with the current state
920 current = {}
921 for prop_n in self._props.keys():
922 prop = self[prop_n]
923 if not isinstance(prop, HTMLProperty):
924 continue
925 current[prop_n] = prop.plain(escape=1)
926 # make link if hrefable
927 if (self._props.has_key(prop_n) and
928 isinstance(self._props[prop_n], hyperdb.Link)):
929 classname = self._props[prop_n].classname
930 try:
931 template = find_template(self._db.config.TEMPLATES,
932 classname, 'item')
933 if template[1].startswith('_generic'):
934 raise NoTemplate, 'not really...'
935 except NoTemplate:
936 pass
937 else:
938 id = self._klass.get(self._nodeid, prop_n, None)
939 current[prop_n] = '<a href="%s%s">%s</a>'%(
940 classname, id, current[prop_n])
941
942 # get the journal, sort and reverse
943 history = self._klass.history(self._nodeid)
944 history.sort()
945 history.reverse()
946
947 # restrict the volume
948 if limit:
949 history = history[:limit]
950
951 timezone = self._db.getUserTimezone()
952 l = []
953 comments = {}
954 for id, evt_date, user, action, args in history:
955 date_s = str(evt_date.local(timezone)).replace("."," ")
956 arg_s = ''
957 if action == 'link' and type(args) == type(()):
958 if len(args) == 3:
959 linkcl, linkid, key = args
960 arg_s += '<a href="%s%s">%s%s %s</a>'%(linkcl, linkid,
961 linkcl, linkid, key)
962 else:
963 arg_s = str(args)
964
965 elif action == 'unlink' and type(args) == type(()):
966 if len(args) == 3:
967 linkcl, linkid, key = args
968 arg_s += '<a href="%s%s">%s%s %s</a>'%(linkcl, linkid,
969 linkcl, linkid, key)
970 else:
971 arg_s = str(args)
972
973 elif type(args) == type({}):
974 cell = []
975 for k in args.keys():
976 # try to get the relevant property and treat it
977 # specially
978 try:
979 prop = self._props[k]
980 except KeyError:
981 prop = None
982 if prop is None:
983 # property no longer exists
984 comments['no_exist'] = self._(
985 "<em>The indicated property no longer exists</em>")
986 cell.append(self._('<em>%s: %s</em>\n')
987 % (self._(k), str(args[k])))
988 continue
989
990 if args[k] and (isinstance(prop, hyperdb.Multilink) or
991 isinstance(prop, hyperdb.Link)):
992 # figure what the link class is
993 classname = prop.classname
994 try:
995 linkcl = self._db.getclass(classname)
996 except KeyError:
997 labelprop = None
998 comments[classname] = self._(
999 "The linked class %(classname)s no longer exists"
1000 ) % locals()
1001 labelprop = linkcl.labelprop(1)
1002 try:
1003 template = find_template(self._db.config.TEMPLATES,
1004 classname, 'item')
1005 if template[1].startswith('_generic'):
1006 raise NoTemplate, 'not really...'
1007 hrefable = 1
1008 except NoTemplate:
1009 hrefable = 0
1010
1011 if isinstance(prop, hyperdb.Multilink) and args[k]:
1012 ml = []
1013 for linkid in args[k]:
1014 if isinstance(linkid, type(())):
1015 sublabel = linkid[0] + ' '
1016 linkids = linkid[1]
1017 else:
1018 sublabel = ''
1019 linkids = [linkid]
1020 subml = []
1021 for linkid in linkids:
1022 label = classname + linkid
1023 # if we have a label property, try to use it
1024 # TODO: test for node existence even when
1025 # there's no labelprop!
1026 try:
1027 if labelprop is not None and \
1028 labelprop != 'id':
1029 label = linkcl.get(linkid, labelprop)
1030 label = cgi.escape(label)
1031 except IndexError:
1032 comments['no_link'] = self._(
1033 "<strike>The linked node"
1034 " no longer exists</strike>")
1035 subml.append('<strike>%s</strike>'%label)
1036 else:
1037 if hrefable:
1038 subml.append('<a href="%s%s">%s</a>'%(
1039 classname, linkid, label))
1040 elif label is None:
1041 subml.append('%s%s'%(classname,
1042 linkid))
1043 else:
1044 subml.append(label)
1045 ml.append(sublabel + ', '.join(subml))
1046 cell.append('%s:\n %s'%(self._(k), ', '.join(ml)))
1047 elif isinstance(prop, hyperdb.Link) and args[k]:
1048 label = classname + args[k]
1049 # if we have a label property, try to use it
1050 # TODO: test for node existence even when
1051 # there's no labelprop!
1052 if labelprop is not None and labelprop != 'id':
1053 try:
1054 label = cgi.escape(linkcl.get(args[k],
1055 labelprop))
1056 except IndexError:
1057 comments['no_link'] = self._(
1058 "<strike>The linked node"
1059 " no longer exists</strike>")
1060 cell.append(' <strike>%s</strike>,\n'%label)
1061 # "flag" this is done .... euwww
1062 label = None
1063 if label is not None:
1064 if hrefable:
1065 old = '<a href="%s%s">%s</a>'%(classname,
1066 args[k], label)
1067 else:
1068 old = label;
1069 cell.append('%s: %s' % (self._(k), old))
1070 if current.has_key(k):
1071 cell[-1] += ' -> %s'%current[k]
1072 current[k] = old
1073
1074 elif isinstance(prop, hyperdb.Date) and args[k]:
1075 if args[k] is None:
1076 d = ''
1077 else:
1078 d = date.Date(args[k],
1079 translator=self._client).local(timezone)
1080 cell.append('%s: %s'%(self._(k), str(d)))
1081 if current.has_key(k):
1082 cell[-1] += ' -> %s' % current[k]
1083 current[k] = str(d)
1084
1085 elif isinstance(prop, hyperdb.Interval) and args[k]:
1086 val = str(date.Interval(args[k],
1087 translator=self._client))
1088 cell.append('%s: %s'%(self._(k), val))
1089 if current.has_key(k):
1090 cell[-1] += ' -> %s'%current[k]
1091 current[k] = val
1092
1093 elif isinstance(prop, hyperdb.String) and args[k]:
1094 val = cgi.escape(args[k])
1095 cell.append('%s: %s'%(self._(k), val))
1096 if current.has_key(k):
1097 cell[-1] += ' -> %s'%current[k]
1098 current[k] = val
1099
1100 elif isinstance(prop, hyperdb.Boolean) and args[k] is not None:
1101 val = args[k] and ''"Yes" or ''"No"
1102 cell.append('%s: %s'%(self._(k), val))
1103 if current.has_key(k):
1104 cell[-1] += ' -> %s'%current[k]
1105 current[k] = val
1106
1107 elif not args[k]:
1108 if current.has_key(k):
1109 cell.append('%s: %s'%(self._(k), current[k]))
1110 current[k] = '(no value)'
1111 else:
1112 cell.append(self._('%s: (no value)')%self._(k))
1113
1114 else:
1115 cell.append('%s: %s'%(self._(k), str(args[k])))
1116 if current.has_key(k):
1117 cell[-1] += ' -> %s'%current[k]
1118 current[k] = str(args[k])
1119
1120 arg_s = '<br />'.join(cell)
1121 else:
1122 # unkown event!!
1123 comments['unknown'] = self._(
1124 "<strong><em>This event is not handled"
1125 " by the history display!</em></strong>")
1126 arg_s = '<strong><em>' + str(args) + '</em></strong>'
1127 date_s = date_s.replace(' ', '&nbsp;')
1128 # if the user's an itemid, figure the username (older journals
1129 # have the username)
1130 if dre.match(user):
1131 user = self._db.user.get(user, 'username')
1132 l.append('<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>'%(
1133 date_s, user, self._(action), arg_s))
1134 if comments:
1135 l.append(self._(
1136 '<tr><td colspan=4><strong>Note:</strong></td></tr>'))
1137 for entry in comments.values():
1138 l.append('<tr><td colspan=4>%s</td></tr>'%entry)
1139
1140 if direction == 'ascending':
1141 l.reverse()
1142
1143 l[0:0] = ['<table class="history">'
1144 '<tr><th colspan="4" class="header">',
1145 self._('History'),
1146 '</th></tr><tr>',
1147 self._('<th>Date</th>'),
1148 self._('<th>User</th>'),
1149 self._('<th>Action</th>'),
1150 self._('<th>Args</th>'),
1151 '</tr>']
1152 l.append('</table>')
1153 return '\n'.join(l)
1154
1155 def renderQueryForm(self):
1156 """ Render this item, which is a query, as a search form.
1157 """
1158 # create a new request and override the specified args
1159 req = HTMLRequest(self._client)
1160 req.classname = self._klass.get(self._nodeid, 'klass')
1161 name = self._klass.get(self._nodeid, 'name')
1162 req.updateFromURL(self._klass.get(self._nodeid, 'url') +
1163 '&@queryname=%s'%urllib.quote(name))
1164
1165 # new template, using the specified classname and request
1166 pt = self._client.instance.templates.get(req.classname, 'search')
1167 # The context for a search page should be the class, not any
1168 # node.
1169 self._client.nodeid = None
1170
1171 # use our fabricated request
1172 return pt.render(self._client, req.classname, req)
1173
1174 def download_url(self):
1175 """ Assume that this item is a FileClass and that it has a name
1176 and content. Construct a URL for the download of the content.
1177 """
1178 name = self._klass.get(self._nodeid, 'name')
1179 url = '%s%s/%s'%(self._classname, self._nodeid, name)
1180 return urllib.quote(url)
1181
1182 def copy_url(self, exclude=("messages", "files")):
1183 """Construct a URL for creating a copy of this item
1184
1185 "exclude" is an optional list of properties that should
1186 not be copied to the new object. By default, this list
1187 includes "messages" and "files" properties. Note that
1188 "id" property cannot be copied.
1189
1190 """
1191 exclude = ("id", "activity", "actor", "creation", "creator") \
1192 + tuple(exclude)
1193 query = {
1194 "@template": "item",
1195 "@note": self._("Copy of %(class)s %(id)s") % {
1196 "class": self._(self._classname), "id": self._nodeid},
1197 }
1198 for name in self._props.keys():
1199 if name not in exclude:
1200 query[name] = self[name].plain()
1201 return self._classname + "?" + "&".join(
1202 ["%s=%s" % (key, urllib.quote(value))
1203 for key, value in query.items()])
1204
1205class _HTMLUser(_HTMLItem):
1206 """Add ability to check for permissions on users.
1207 """
1208 _marker = []
1209 def hasPermission(self, permission, classname=_marker,
1210 property=None, itemid=None):
1211 """Determine if the user has the Permission.
1212
1213 The class being tested defaults to the template's class, but may
1214 be overidden for this test by suppling an alternate classname.
1215 """
1216 if classname is self._marker:
1217 classname = self._client.classname
1218 return self._db.security.hasPermission(permission,
1219 self._nodeid, classname, property, itemid)
1220
1221 def hasRole(self, *rolenames):
1222 """Determine whether the user has any role in rolenames."""
1223 return self._db.user.has_role(self._nodeid, *rolenames)
1224
1225def HTMLItem(client, classname, nodeid, anonymous=0):
1226 if classname == 'user':
1227 return _HTMLUser(client, classname, nodeid, anonymous)
1228 else:
1229 return _HTMLItem(client, classname, nodeid, anonymous)
1230
1231class HTMLProperty(HTMLInputMixin, HTMLPermissions):
1232 """ String, Number, Date, Interval HTMLProperty
1233
1234 Has useful attributes:
1235
1236 _name the name of the property
1237 _value the value of the property if any
1238
1239 A wrapper object which may be stringified for the plain() behaviour.
1240 """
1241 def __init__(self, client, classname, nodeid, prop, name, value,
1242 anonymous=0):
1243 self._client = client
1244 self._db = client.db
1245 self._ = client._
1246 self._classname = classname
1247 self._nodeid = nodeid
1248 self._prop = prop
1249 self._value = value
1250 self._anonymous = anonymous
1251 self._name = name
1252 if not anonymous:
1253 if nodeid:
1254 self._formname = '%s%s@%s'%(classname, nodeid, name)
1255 else:
1256 # This case occurs when creating a property for a
1257 # non-anonymous class.
1258 self._formname = '%s@%s'%(classname, name)
1259 else:
1260 self._formname = name
1261
1262 # If no value is already present for this property, see if one
1263 # is specified in the current form.
1264 form = self._client.form
1265 if not self._value and form.has_key(self._formname):
1266 if isinstance(prop, hyperdb.Multilink):
1267 value = lookupIds(self._db, prop,
1268 handleListCGIValue(form[self._formname]),
1269 fail_ok=1)
1270 elif isinstance(prop, hyperdb.Link):
1271 value = form.getfirst(self._formname).strip()
1272 if value:
1273 value = lookupIds(self._db, prop, [value],
1274 fail_ok=1)[0]
1275 else:
1276 value = None
1277 else:
1278 value = form.getfirst(self._formname).strip() or None
1279 self._value = value
1280
1281 HTMLInputMixin.__init__(self)
1282
1283 def __repr__(self):
1284 return '<HTMLProperty(0x%x) %s %r %r>'%(id(self), self._formname,
1285 self._prop, self._value)
1286 def __str__(self):
1287 return self.plain()
1288 def __cmp__(self, other):
1289 if isinstance(other, HTMLProperty):
1290 return cmp(self._value, other._value)
1291 return cmp(self._value, other)
1292
1293 def __nonzero__(self):
1294 return not not self._value
1295
1296 def isset(self):
1297 """Is my _value not None?"""
1298 return self._value is not None
1299
1300 def is_edit_ok(self):
1301 """Should the user be allowed to use an edit form field for this
1302 property. Check "Create" for new items, or "Edit" for existing
1303 ones.
1304 """
1305 perm = self._db.security.hasPermission
1306 userid = self._client.userid
1307 if self._nodeid:
1308 if not perm('Web Access', userid):
1309 return False
1310 return perm('Edit', userid, self._classname, self._name,
1311 self._nodeid)
1312 return perm('Create', userid, self._classname, self._name) or \
1313 perm('Register', userid, self._classname, self._name)
1314
1315 def is_view_ok(self):
1316 """ Is the user allowed to View the current class?
1317 """
1318 perm = self._db.security.hasPermission
1319 if perm('Web Access', self._client.userid) and perm('View',
1320 self._client.userid, self._classname, self._name, self._nodeid):
1321 return 1
1322 return self.is_edit_ok()
1323
1324class StringHTMLProperty(HTMLProperty):
1325 hyper_re = re.compile(r'''(
1326 (?P<url>
1327 (
1328 (ht|f)tp(s?):// # protocol
1329 ([\w]+(:\w+)?@)? # username/password
1330 ([\w\-]+) # hostname
1331 ((\.[\w-]+)+)? # .domain.etc
1332 | # ... or ...
1333 ([\w]+(:\w+)?@)? # username/password
1334 www\. # "www."
1335 ([\w\-]+\.)+ # hostname
1336 [\w]{2,5} # TLD
1337 )
1338 (:[\d]{1,5})? # port
1339 (/[\w\-$.+!*(),;:@&=?/~\\#%]*)? # path etc.
1340 )|
1341 (?P<email>[-+=%/\w\.]+@[\w\.\-]+)|
1342 (?P<item>(?P<class>[A-Za-z_]+)(\s*)(?P<id>\d+))
1343 )''', re.X | re.I)
1344 protocol_re = re.compile('^(ht|f)tp(s?)://', re.I)
1345
1346 def _hyper_repl_item(self,match,replacement):
1347 item = match.group('item')
1348 cls = match.group('class').lower()
1349 id = match.group('id')
1350 try:
1351 # make sure cls is a valid tracker classname
1352 cl = self._db.getclass(cls)
1353 if not cl.hasnode(id):
1354 return item
1355 return replacement % locals()
1356 except KeyError:
1357 return item
1358
1359 def _hyper_repl(self, match):
1360 if match.group('url'):
1361 u = s = match.group('url')
1362 if not self.protocol_re.search(s):
1363 u = 'http://' + s
1364 # catch an escaped ">" at the end of the URL
1365 if s.endswith('&gt;'):
1366 u = s = s[:-4]
1367 e = '&gt;'
1368 else:
1369 e = ''
1370 return '<a href="%s">%s</a>%s'%(u, s, e)
1371 elif match.group('email'):
1372 s = match.group('email')
1373 return '<a href="mailto:%s">%s</a>'%(s, s)
1374 elif len(match.group('id')) < 10:
1375 return self._hyper_repl_item(match,
1376 '<a href="%(cls)s%(id)s">%(item)s</a>')
1377 else:
1378 # just return the matched text
1379 return match.group(0)
1380
1381 def _hyper_repl_rst(self, match):
1382 if match.group('url'):
1383 s = match.group('url')
1384 return '`%s <%s>`_'%(s, s)
1385 elif match.group('email'):
1386 s = match.group('email')
1387 return '`%s <mailto:%s>`_'%(s, s)
1388 elif len(match.group('id')) < 10:
1389 return self._hyper_repl_item(match,'`%(item)s <%(cls)s%(id)s>`_')
1390 else:
1391 # just return the matched text
1392 return match.group(0)
1393
1394 def hyperlinked(self):
1395 """ Render a "hyperlinked" version of the text """
1396 return self.plain(hyperlink=1)
1397
1398 def plain(self, escape=0, hyperlink=0):
1399 """Render a "plain" representation of the property
1400
1401 - "escape" turns on/off HTML quoting
1402 - "hyperlink" turns on/off in-text hyperlinking of URLs, email
1403 addresses and designators
1404 """
1405 if not self.is_view_ok():
1406 return self._('[hidden]')
1407
1408 if self._value is None:
1409 return ''
1410 if escape:
1411 s = cgi.escape(str(self._value))
1412 else:
1413 s = str(self._value)
1414 if hyperlink:
1415 # no, we *must* escape this text
1416 if not escape:
1417 s = cgi.escape(s)
1418 s = self.hyper_re.sub(self._hyper_repl, s)
1419 return s
1420
1421 def wrapped(self, escape=1, hyperlink=1):
1422 """Render a "wrapped" representation of the property.
1423
1424 We wrap long lines at 80 columns on the nearest whitespace. Lines
1425 with no whitespace are not broken to force wrapping.
1426
1427 Note that unlike plain() we default wrapped() to have the escaping
1428 and hyperlinking turned on since that's the most common usage.
1429
1430 - "escape" turns on/off HTML quoting
1431 - "hyperlink" turns on/off in-text hyperlinking of URLs, email
1432 addresses and designators
1433 """
1434 if not self.is_view_ok():
1435 return self._('[hidden]')
1436
1437 if self._value is None:
1438 return ''
1439 s = support.wrap(str(self._value), width=80)
1440 if escape:
1441 s = cgi.escape(s)
1442 if hyperlink:
1443 # no, we *must* escape this text
1444 if not escape:
1445 s = cgi.escape(s)
1446 s = self.hyper_re.sub(self._hyper_repl, s)
1447 return s
1448
1449 def stext(self, escape=0, hyperlink=1):
1450 """ Render the value of the property as StructuredText.
1451
1452 This requires the StructureText module to be installed separately.
1453 """
1454 if not self.is_view_ok():
1455 return self._('[hidden]')
1456
1457 s = self.plain(escape=escape, hyperlink=hyperlink)
1458 if not StructuredText:
1459 return s
1460 return StructuredText(s,level=1,header=0)
1461
1462 def rst(self, hyperlink=1):
1463 """ Render the value of the property as ReStructuredText.
1464
1465 This requires docutils to be installed separately.
1466 """
1467 if not self.is_view_ok():
1468 return self._('[hidden]')
1469
1470 if not ReStructuredText:
1471 return self.plain(escape=0, hyperlink=hyperlink)
1472 s = self.plain(escape=0, hyperlink=0)
1473 if hyperlink:
1474 s = self.hyper_re.sub(self._hyper_repl_rst, s)
1475 return ReStructuredText(s, writer_name="html")["html_body"].encode("utf-8",
1476 "replace")
1477
1478 def field(self, **kwargs):
1479 """ Render the property as a field in HTML.
1480
1481 If not editable, just display the value via plain().
1482 """
1483 if not self.is_edit_ok():
1484 return self.plain(escape=1)
1485
1486 value = self._value
1487 if value is None:
1488 value = ''
1489
1490 kwargs.setdefault("size", 30)
1491 kwargs.update({"name": self._formname, "value": value})
1492 return self.input(**kwargs)
1493
1494 def multiline(self, escape=0, rows=5, cols=40, **kwargs):
1495 """ Render a multiline form edit field for the property.
1496
1497 If not editable, just display the plain() value in a <pre> tag.
1498 """
1499 if not self.is_edit_ok():
1500 return '<pre>%s</pre>'%self.plain()
1501
1502 if self._value is None:
1503 value = ''
1504 else:
1505 value = cgi.escape(str(self._value))
1506
1507 value = '&quot;'.join(value.split('"'))
1508 name = self._formname
1509 passthrough_args = cgi_escape_attrs(**kwargs)
1510 return ('<textarea %(passthrough_args)s name="%(name)s" id="%(name)s"'
1511 ' rows="%(rows)s" cols="%(cols)s">'
1512 '%(value)s</textarea>') % locals()
1513
1514 def email(self, escape=1):
1515 """ Render the value of the property as an obscured email address
1516 """
1517 if not self.is_view_ok():
1518 return self._('[hidden]')
1519
1520 if self._value is None:
1521 value = ''
1522 else:
1523 value = str(self._value)
1524 split = value.split('@')
1525 if len(split) == 2:
1526 name, domain = split
1527 domain = ' '.join(domain.split('.')[:-1])
1528 name = name.replace('.', ' ')
1529 value = '%s at %s ...'%(name, domain)
1530 else:
1531 value = value.replace('.', ' ')
1532 if escape:
1533 value = cgi.escape(value)
1534 return value
1535
1536class PasswordHTMLProperty(HTMLProperty):
1537 def plain(self, escape=0):
1538 """ Render a "plain" representation of the property
1539 """
1540 if not self.is_view_ok():
1541 return self._('[hidden]')
1542
1543 if self._value is None:
1544 return ''
1545 return self._('*encrypted*')
1546
1547 def field(self, size=30, **kwargs):
1548 """ Render a form edit field for the property.
1549
1550 If not editable, just display the value via plain().
1551 """
1552 if not self.is_edit_ok():
1553 return self.plain(escape=1)
1554
1555 return self.input(type="password", name=self._formname, size=size,
1556 **kwargs)
1557
1558 def confirm(self, size=30):
1559 """ Render a second form edit field for the property, used for
1560 confirmation that the user typed the password correctly. Generates
1561 a field with name "@confirm@name".
1562
1563 If not editable, display nothing.
1564 """
1565 if not self.is_edit_ok():
1566 return ''
1567
1568 return self.input(type="password",
1569 name="@confirm@%s"%self._formname,
1570 id="%s-confirm"%self._formname,
1571 size=size)
1572
1573class NumberHTMLProperty(HTMLProperty):
1574 def plain(self, escape=0):
1575 """ Render a "plain" representation of the property
1576 """
1577 if not self.is_view_ok():
1578 return self._('[hidden]')
1579
1580 if self._value is None:
1581 return ''
1582
1583 return str(self._value)
1584
1585 def field(self, size=30, **kwargs):
1586 """ Render a form edit field for the property.
1587
1588 If not editable, just display the value via plain().
1589 """
1590 if not self.is_edit_ok():
1591 return self.plain(escape=1)
1592
1593 value = self._value
1594 if value is None:
1595 value = ''
1596
1597 return self.input(name=self._formname, value=value, size=size,
1598 **kwargs)
1599
1600 def __int__(self):
1601 """ Return an int of me
1602 """
1603 return int(self._value)
1604
1605 def __float__(self):
1606 """ Return a float of me
1607 """
1608 return float(self._value)
1609
1610
1611class BooleanHTMLProperty(HTMLProperty):
1612 def plain(self, escape=0):
1613 """ Render a "plain" representation of the property
1614 """
1615 if not self.is_view_ok():
1616 return self._('[hidden]')
1617
1618 if self._value is None:
1619 return ''
1620 return self._value and self._("Yes") or self._("No")
1621
1622 def field(self, **kwargs):
1623 """ Render a form edit field for the property
1624
1625 If not editable, just display the value via plain().
1626 """
1627 if not self.is_edit_ok():
1628 return self.plain(escape=1)
1629
1630 value = self._value
1631 if isinstance(value, str) or isinstance(value, unicode):
1632 value = value.strip().lower() in ('checked', 'yes', 'true',
1633 'on', '1')
1634
1635 checked = value and "checked" or ""
1636 if value:
1637 s = self.input(type="radio", name=self._formname, value="yes",
1638 checked="checked", **kwargs)
1639 s += self._('Yes')
1640 s +=self.input(type="radio", name=self._formname, value="no",
1641 **kwargs)
1642 s += self._('No')
1643 else:
1644 s = self.input(type="radio", name=self._formname, value="yes",
1645 **kwargs)
1646 s += self._('Yes')
1647 s +=self.input(type="radio", name=self._formname, value="no",
1648 checked="checked", **kwargs)
1649 s += self._('No')
1650 return s
1651
1652class DateHTMLProperty(HTMLProperty):
1653
1654 _marker = []
1655
1656 def __init__(self, client, classname, nodeid, prop, name, value,
1657 anonymous=0, offset=None):
1658 HTMLProperty.__init__(self, client, classname, nodeid, prop, name,
1659 value, anonymous=anonymous)
1660 if self._value and not (isinstance(self._value, str) or
1661 isinstance(self._value, unicode)):
1662 self._value.setTranslator(self._client.translator)
1663 self._offset = offset
1664 if self._offset is None :
1665 self._offset = self._prop.offset (self._db)
1666
1667 def plain(self, escape=0):
1668 """ Render a "plain" representation of the property
1669 """
1670 if not self.is_view_ok():
1671 return self._('[hidden]')
1672
1673 if self._value is None:
1674 return ''
1675 if self._offset is None:
1676 offset = self._db.getUserTimezone()
1677 else:
1678 offset = self._offset
1679 return str(self._value.local(offset))
1680
1681 def now(self, str_interval=None):
1682 """ Return the current time.
1683
1684 This is useful for defaulting a new value. Returns a
1685 DateHTMLProperty.
1686 """
1687 if not self.is_view_ok():
1688 return self._('[hidden]')
1689
1690 ret = date.Date('.', translator=self._client)
1691
1692 if isinstance(str_interval, basestring):
1693 sign = 1
1694 if str_interval[0] == '-':
1695 sign = -1
1696 str_interval = str_interval[1:]
1697 interval = date.Interval(str_interval, translator=self._client)
1698 if sign > 0:
1699 ret = ret + interval
1700 else:
1701 ret = ret - interval
1702
1703 return DateHTMLProperty(self._client, self._classname, self._nodeid,
1704 self._prop, self._formname, ret)
1705
1706 def field(self, size=30, default=None, format=_marker, popcal=True,
1707 **kwargs):
1708 """Render a form edit field for the property
1709
1710 If not editable, just display the value via plain().
1711
1712 If "popcal" then include the Javascript calendar editor.
1713 Default=yes.
1714
1715 The format string is a standard python strftime format string.
1716 """
1717 if not self.is_edit_ok():
1718 if format is self._marker:
1719 return self.plain(escape=1)
1720 else:
1721 return self.pretty(format)
1722
1723 value = self._value
1724
1725 if value is None:
1726 if default is None:
1727 raw_value = None
1728 else:
1729 if isinstance(default, basestring):
1730 raw_value = date.Date(default, translator=self._client)
1731 elif isinstance(default, date.Date):
1732 raw_value = default
1733 elif isinstance(default, DateHTMLProperty):
1734 raw_value = default._value
1735 else:
1736 raise ValueError, self._('default value for '
1737 'DateHTMLProperty must be either DateHTMLProperty '
1738 'or string date representation.')
1739 elif isinstance(value, str) or isinstance(value, unicode):
1740 # most likely erroneous input to be passed back to user
1741 if isinstance(value, unicode): value = value.encode('utf8')
1742 return self.input(name=self._formname, value=value, size=size,
1743 **kwargs)
1744 else:
1745 raw_value = value
1746
1747 if raw_value is None:
1748 value = ''
1749 elif isinstance(raw_value, str) or isinstance(raw_value, unicode):
1750 if format is self._marker:
1751 value = raw_value
1752 else:
1753 value = date.Date(raw_value).pretty(format)
1754 else:
1755 if self._offset is None :
1756 offset = self._db.getUserTimezone()
1757 else :
1758 offset = self._offset
1759 value = raw_value.local(offset)
1760 if format is not self._marker:
1761 value = value.pretty(format)
1762
1763 s = self.input(name=self._formname, value=value, size=size,
1764 **kwargs)
1765 if popcal:
1766 s += self.popcal()
1767 return s
1768
1769 def reldate(self, pretty=1):
1770 """ Render the interval between the date and now.
1771
1772 If the "pretty" flag is true, then make the display pretty.
1773 """
1774 if not self.is_view_ok():
1775 return self._('[hidden]')
1776
1777 if not self._value:
1778 return ''
1779
1780 # figure the interval
1781 interval = self._value - date.Date('.', translator=self._client)
1782 if pretty:
1783 return interval.pretty()
1784 return str(interval)
1785
1786 def pretty(self, format=_marker):
1787 """ Render the date in a pretty format (eg. month names, spaces).
1788
1789 The format string is a standard python strftime format string.
1790 Note that if the day is zero, and appears at the start of the
1791 string, then it'll be stripped from the output. This is handy
1792 for the situation when a date only specifies a month and a year.
1793 """
1794 if not self.is_view_ok():
1795 return self._('[hidden]')
1796
1797 if self._offset is None:
1798 offset = self._db.getUserTimezone()
1799 else:
1800 offset = self._offset
1801
1802 if not self._value:
1803 return ''
1804 elif format is not self._marker:
1805 return self._value.local(offset).pretty(format)
1806 else:
1807 return self._value.local(offset).pretty()
1808
1809 def local(self, offset):
1810 """ Return the date/time as a local (timezone offset) date/time.
1811 """
1812 if not self.is_view_ok():
1813 return self._('[hidden]')
1814
1815 return DateHTMLProperty(self._client, self._classname, self._nodeid,
1816 self._prop, self._formname, self._value, offset=offset)
1817
1818 def popcal(self, width=300, height=200, label="(cal)",
1819 form="itemSynopsis"):
1820 """Generate a link to a calendar pop-up window.
1821
1822 item: HTMLProperty e.g.: context.deadline
1823 """
1824 if self.isset():
1825 date = "&date=%s"%self._value
1826 else :
1827 date = ""
1828 return ('<a class="classhelp" href="javascript:help_window('
1829 "'%s?@template=calendar&amp;property=%s&amp;form=%s%s', %d, %d)"
1830 '">%s</a>'%(self._classname, self._name, form, date, width,
1831 height, label))
1832
1833class IntervalHTMLProperty(HTMLProperty):
1834 def __init__(self, client, classname, nodeid, prop, name, value,
1835 anonymous=0):
1836 HTMLProperty.__init__(self, client, classname, nodeid, prop,
1837 name, value, anonymous)
1838 if self._value and not isinstance(self._value, (str, unicode)):
1839 self._value.setTranslator(self._client.translator)
1840
1841 def plain(self, escape=0):
1842 """ Render a "plain" representation of the property
1843 """
1844 if not self.is_view_ok():
1845 return self._('[hidden]')
1846
1847 if self._value is None:
1848 return ''
1849 return str(self._value)
1850
1851 def pretty(self):
1852 """ Render the interval in a pretty format (eg. "yesterday")
1853 """
1854 if not self.is_view_ok():
1855 return self._('[hidden]')
1856
1857 return self._value.pretty()
1858
1859 def field(self, size=30, **kwargs):
1860 """ Render a form edit field for the property
1861
1862 If not editable, just display the value via plain().
1863 """
1864 if not self.is_edit_ok():
1865 return self.plain(escape=1)
1866
1867 value = self._value
1868 if value is None:
1869 value = ''
1870
1871 return self.input(name=self._formname, value=value, size=size,
1872 **kwargs)
1873
1874class LinkHTMLProperty(HTMLProperty):
1875 """ Link HTMLProperty
1876 Include the above as well as being able to access the class
1877 information. Stringifying the object itself results in the value
1878 from the item being displayed. Accessing attributes of this object
1879 result in the appropriate entry from the class being queried for the
1880 property accessed (so item/assignedto/name would look up the user
1881 entry identified by the assignedto property on item, and then the
1882 name property of that user)
1883 """
1884 def __init__(self, *args, **kw):
1885 HTMLProperty.__init__(self, *args, **kw)
1886 # if we're representing a form value, then the -1 from the form really
1887 # should be a None
1888 if str(self._value) == '-1':
1889 self._value = None
1890
1891 def __getattr__(self, attr):
1892 """ return a new HTMLItem """
1893 if not self._value:
1894 # handle a special page templates lookup
1895 if attr == '__render_with_namespace__':
1896 def nothing(*args, **kw):
1897 return ''
1898 return nothing
1899 msg = self._('Attempt to look up %(attr)s on a missing value')
1900 return MissingValue(msg%locals())
1901 i = HTMLItem(self._client, self._prop.classname, self._value)
1902 return getattr(i, attr)
1903
1904 def plain(self, escape=0):
1905 """ Render a "plain" representation of the property
1906 """
1907 if not self.is_view_ok():
1908 return self._('[hidden]')
1909
1910 if self._value is None:
1911 return ''
1912 linkcl = self._db.classes[self._prop.classname]
1913 k = linkcl.labelprop(1)
1914 if num_re.match(self._value):
1915 try:
1916 value = str(linkcl.get(self._value, k))
1917 except IndexError:
1918 value = self._value
1919 else :
1920 value = self._value
1921 if escape:
1922 value = cgi.escape(value)
1923 return value
1924
1925 def field(self, showid=0, size=None, **kwargs):
1926 """ Render a form edit field for the property
1927
1928 If not editable, just display the value via plain().
1929 """
1930 if not self.is_edit_ok():
1931 return self.plain(escape=1)
1932
1933 # edit field
1934 linkcl = self._db.getclass(self._prop.classname)
1935 if self._value is None:
1936 value = ''
1937 else:
1938 k = linkcl.getkey()
1939 if k and num_re.match(self._value):
1940 value = linkcl.get(self._value, k)
1941 else:
1942 value = self._value
1943 return self.input(name=self._formname, value=value, size=size,
1944 **kwargs)
1945
1946 def menu(self, size=None, height=None, showid=0, additional=[], value=None,
1947 sort_on=None, html_kwargs = {}, **conditions):
1948 """ Render a form select list for this property
1949
1950 "size" is used to limit the length of the list labels
1951 "height" is used to set the <select> tag's "size" attribute
1952 "showid" includes the item ids in the list labels
1953 "value" specifies which item is pre-selected
1954 "additional" lists properties which should be included in the
1955 label
1956 "sort_on" indicates the property to sort the list on as
1957 (direction, property) where direction is '+' or '-'. A
1958 single string with the direction prepended may be used.
1959 For example: ('-', 'order'), '+name'.
1960
1961 The remaining keyword arguments are used as conditions for
1962 filtering the items in the list - they're passed as the
1963 "filterspec" argument to a Class.filter() call.
1964
1965 If not editable, just display the value via plain().
1966 """
1967 if not self.is_edit_ok():
1968 return self.plain(escape=1)
1969
1970 # Since None indicates the default, we need another way to
1971 # indicate "no selection". We use -1 for this purpose, as
1972 # that is the value we use when submitting a form without the
1973 # value set.
1974 if value is None:
1975 value = self._value
1976 elif value == '-1':
1977 value = None
1978
1979 linkcl = self._db.getclass(self._prop.classname)
1980 l = ['<select %s>'%cgi_escape_attrs(name = self._formname,
1981 **html_kwargs)]
1982 k = linkcl.labelprop(1)
1983 s = ''
1984 if value is None:
1985 s = 'selected="selected" '
1986 l.append(self._('<option %svalue="-1">- no selection -</option>')%s)
1987
1988 if sort_on is not None:
1989 if not isinstance(sort_on, tuple):
1990 if sort_on[0] in '+-':
1991 sort_on = (sort_on[0], sort_on[1:])
1992 else:
1993 sort_on = ('+', sort_on)
1994 else:
1995 sort_on = ('+', linkcl.orderprop())
1996
1997 options = [opt
1998 for opt in linkcl.filter(None, conditions, sort_on, (None, None))
1999 if self._db.security.hasPermission("View", self._client.userid,
2000 linkcl.classname, itemid=opt)]
2001
2002 # make sure we list the current value if it's retired
2003 if value and value not in options:
2004 options.insert(0, value)
2005
2006 if additional:
2007 additional_fns = []
2008 props = linkcl.getprops()
2009 for propname in additional:
2010 prop = props[propname]
2011 if isinstance(prop, hyperdb.Link):
2012 cl = self._db.getclass(prop.classname)
2013 labelprop = cl.labelprop()
2014 fn = lambda optionid: cl.get(linkcl.get(optionid,
2015 propname),
2016 labelprop)
2017 else:
2018 fn = lambda optionid: linkcl.get(optionid, propname)
2019 additional_fns.append(fn)
2020
2021 for optionid in options:
2022 # get the option value, and if it's None use an empty string
2023 option = linkcl.get(optionid, k) or ''
2024
2025 # figure if this option is selected
2026 s = ''
2027 if value in [optionid, option]:
2028 s = 'selected="selected" '
2029
2030 # figure the label
2031 if showid:
2032 lab = '%s%s: %s'%(self._prop.classname, optionid, option)
2033 elif not option:
2034 lab = '%s%s'%(self._prop.classname, optionid)
2035 else:
2036 lab = option
2037
2038 # truncate if it's too long
2039 if size is not None and len(lab) > size:
2040 lab = lab[:size-3] + '...'
2041 if additional:
2042 m = []
2043 for fn in additional_fns:
2044 m.append(str(fn(optionid)))
2045 lab = lab + ' (%s)'%', '.join(m)
2046
2047 # and generate
2048 lab = cgi.escape(self._(lab))
2049 l.append('<option %svalue="%s">%s</option>'%(s, optionid, lab))
2050 l.append('</select>')
2051 return '\n'.join(l)
2052# def checklist(self, ...)
2053
2054
2055
2056class MultilinkHTMLProperty(HTMLProperty):
2057 """ Multilink HTMLProperty
2058
2059 Also be iterable, returning a wrapper object like the Link case for
2060 each entry in the multilink.
2061 """
2062 def __init__(self, *args, **kwargs):
2063 HTMLProperty.__init__(self, *args, **kwargs)
2064 if self._value:
2065 display_value = lookupIds(self._db, self._prop, self._value,
2066 fail_ok=1, do_lookup=False)
2067 sortfun = make_sort_function(self._db, self._prop.classname)
2068 # sorting fails if the value contains
2069 # items not yet stored in the database
2070 # ignore these errors to preserve user input
2071 try:
2072 display_value.sort(sortfun)
2073 except:
2074 pass
2075 self._value = display_value
2076
2077 def __len__(self):
2078 """ length of the multilink """
2079 return len(self._value)
2080
2081 def __getattr__(self, attr):
2082 """ no extended attribute accesses make sense here """
2083 raise AttributeError, attr
2084
2085 def viewableGenerator(self, values):
2086 """Used to iterate over only the View'able items in a class."""
2087 check = self._db.security.hasPermission
2088 userid = self._client.userid
2089 classname = self._prop.classname
2090 if check('Web Access', userid):
2091 for value in values:
2092 if check('View', userid, classname, itemid=value):
2093 yield HTMLItem(self._client, classname, value)
2094
2095 def __iter__(self):
2096 """ iterate and return a new HTMLItem
2097 """
2098 return self.viewableGenerator(self._value)
2099
2100 def reverse(self):
2101 """ return the list in reverse order
2102 """
2103 l = self._value[:]
2104 l.reverse()
2105 return self.viewableGenerator(l)
2106
2107 def sorted(self, property):
2108 """ Return this multilink sorted by the given property """
2109 value = list(self.__iter__())
2110 value.sort(lambda a,b:cmp(a[property], b[property]))
2111 return value
2112
2113 def __contains__(self, value):
2114 """ Support the "in" operator. We have to make sure the passed-in
2115 value is a string first, not a HTMLProperty.
2116 """
2117 return str(value) in self._value
2118
2119 def isset(self):
2120 """Is my _value not []?"""
2121 return self._value != []
2122
2123 def plain(self, escape=0):
2124 """ Render a "plain" representation of the property
2125 """
2126 if not self.is_view_ok():
2127 return self._('[hidden]')
2128
2129 linkcl = self._db.classes[self._prop.classname]
2130 k = linkcl.labelprop(1)
2131 labels = []
2132 for v in self._value:
2133 if num_re.match(v):
2134 try:
2135 label = linkcl.get(v, k)
2136 except IndexError:
2137 label = None
2138 # fall back to designator if label is None
2139 if label is None: label = '%s%s'%(self._prop.classname, k)
2140 else:
2141 label = v
2142 labels.append(label)
2143 value = ', '.join(labels)
2144 if escape:
2145 value = cgi.escape(value)
2146 return value
2147
2148 def field(self, size=30, showid=0, **kwargs):
2149 """ Render a form edit field for the property
2150
2151 If not editable, just display the value via plain().
2152 """
2153 if not self.is_edit_ok():
2154 return self.plain(escape=1)
2155
2156 linkcl = self._db.getclass(self._prop.classname)
2157
2158 if 'value' not in kwargs:
2159 value = self._value[:]
2160 # map the id to the label property
2161 if not linkcl.getkey():
2162 showid=1
2163 if not showid:
2164 k = linkcl.labelprop(1)
2165 value = lookupKeys(linkcl, k, value)
2166 value = ','.join(value)
2167 kwargs["value"] = value
2168
2169 return self.input(name=self._formname, size=size, **kwargs)
2170
2171 def menu(self, size=None, height=None, showid=0, additional=[],
2172 value=None, sort_on=None, html_kwargs = {}, **conditions):
2173 """ Render a form <select> list for this property.
2174
2175 "size" is used to limit the length of the list labels
2176 "height" is used to set the <select> tag's "size" attribute
2177 "showid" includes the item ids in the list labels
2178 "additional" lists properties which should be included in the
2179 label
2180 "value" specifies which item is pre-selected
2181 "sort_on" indicates the property to sort the list on as
2182 (direction, property) where direction is '+' or '-'. A
2183 single string with the direction prepended may be used.
2184 For example: ('-', 'order'), '+name'.
2185
2186 The remaining keyword arguments are used as conditions for
2187 filtering the items in the list - they're passed as the
2188 "filterspec" argument to a Class.filter() call.
2189
2190 If not editable, just display the value via plain().
2191 """
2192 if not self.is_edit_ok():
2193 return self.plain(escape=1)
2194
2195 if value is None:
2196 value = self._value
2197
2198 linkcl = self._db.getclass(self._prop.classname)
2199
2200 if sort_on is not None:
2201 if not isinstance(sort_on, tuple):
2202 if sort_on[0] in '+-':
2203 sort_on = (sort_on[0], sort_on[1:])
2204 else:
2205 sort_on = ('+', sort_on)
2206 else:
2207 sort_on = ('+', linkcl.orderprop())
2208
2209 options = [opt
2210 for opt in linkcl.filter(None, conditions, sort_on)
2211 if self._db.security.hasPermission("View", self._client.userid,
2212 linkcl.classname, itemid=opt)]
2213
2214 # make sure we list the current values if they're retired
2215 for val in value:
2216 if val not in options:
2217 options.insert(0, val)
2218
2219 if not height:
2220 height = len(options)
2221 if value:
2222 # The "no selection" option.
2223 height += 1
2224 height = min(height, 7)
2225 l = ['<select multiple %s>'%cgi_escape_attrs(name = self._formname,
2226 size = height,
2227 **html_kwargs)]
2228 k = linkcl.labelprop(1)
2229
2230 if value:
2231 l.append('<option value="%s">- no selection -</option>'
2232 % ','.join(['-' + v for v in value]))
2233
2234 if additional:
2235 additional_fns = []
2236 props = linkcl.getprops()
2237 for propname in additional:
2238 prop = props[propname]
2239 if isinstance(prop, hyperdb.Link):
2240 cl = self._db.getclass(prop.classname)
2241 labelprop = cl.labelprop()
2242 fn = lambda optionid: cl.get(linkcl.get(optionid,
2243 propname),
2244 labelprop)
2245 else:
2246 fn = lambda optionid: linkcl.get(optionid, propname)
2247 additional_fns.append(fn)
2248
2249 for optionid in options:
2250 # get the option value, and if it's None use an empty string
2251 option = linkcl.get(optionid, k) or ''
2252
2253 # figure if this option is selected
2254 s = ''
2255 if optionid in value or option in value:
2256 s = 'selected="selected" '
2257
2258 # figure the label
2259 if showid:
2260 lab = '%s%s: %s'%(self._prop.classname, optionid, option)
2261 else:
2262 lab = option
2263 # truncate if it's too long
2264 if size is not None and len(lab) > size:
2265 lab = lab[:size-3] + '...'
2266 if additional:
2267 m = []
2268 for fn in additional_fns:
2269 m.append(str(fn(optionid)))
2270 lab = lab + ' (%s)'%', '.join(m)
2271
2272 # and generate
2273 lab = cgi.escape(self._(lab))
2274 l.append('<option %svalue="%s">%s</option>'%(s, optionid,
2275 lab))
2276 l.append('</select>')
2277 return '\n'.join(l)
2278
2279# set the propclasses for HTMLItem
2280propclasses = (
2281 (hyperdb.String, StringHTMLProperty),
2282 (hyperdb.Number, NumberHTMLProperty),
2283 (hyperdb.Boolean, BooleanHTMLProperty),
2284 (hyperdb.Date, DateHTMLProperty),
2285 (hyperdb.Interval, IntervalHTMLProperty),
2286 (hyperdb.Password, PasswordHTMLProperty),
2287 (hyperdb.Link, LinkHTMLProperty),
2288 (hyperdb.Multilink, MultilinkHTMLProperty),
2289)
2290
2291def make_sort_function(db, classname, sort_on=None):
2292 """Make a sort function for a given class
2293 """
2294 linkcl = db.getclass(classname)
2295 if sort_on is None:
2296 sort_on = linkcl.orderprop()
2297 def sortfunc(a, b):
2298 return cmp(linkcl.get(a, sort_on), linkcl.get(b, sort_on))
2299 return sortfunc
2300
2301def handleListCGIValue(value):
2302 """ Value is either a single item or a list of items. Each item has a
2303 .value that we're actually interested in.
2304 """
2305 if isinstance(value, type([])):
2306 return [value.value for value in value]
2307 else:
2308 value = value.value.strip()
2309 if not value:
2310 return []
2311 return [v.strip() for v in value.split(',')]
2312
2313class HTMLRequest(HTMLInputMixin):
2314 """The *request*, holding the CGI form and environment.
2315
2316 - "form" the CGI form as a cgi.FieldStorage
2317 - "env" the CGI environment variables
2318 - "base" the base URL for this instance
2319 - "user" a HTMLItem instance for this user
2320 - "language" as determined by the browser or config
2321 - "classname" the current classname (possibly None)
2322 - "template" the current template (suffix, also possibly None)
2323
2324 Index args:
2325
2326 - "columns" dictionary of the columns to display in an index page
2327 - "show" a convenience access to columns - request/show/colname will
2328 be true if the columns should be displayed, false otherwise
2329 - "sort" index sort column (direction, column name)
2330 - "group" index grouping property (direction, column name)
2331 - "filter" properties to filter the index on
2332 - "filterspec" values to filter the index on
2333 - "search_text" text to perform a full-text search on for an index
2334 """
2335 def __repr__(self):
2336 return '<HTMLRequest %r>'%self.__dict__
2337
2338 def __init__(self, client):
2339 # _client is needed by HTMLInputMixin
2340 self._client = self.client = client
2341
2342 # easier access vars
2343 self.form = client.form
2344 self.env = client.env
2345 self.base = client.base
2346 self.user = HTMLItem(client, 'user', client.userid)
2347 self.language = client.language
2348
2349 # store the current class name and action
2350 self.classname = client.classname
2351 self.nodeid = client.nodeid
2352 self.template = client.template
2353
2354 # the special char to use for special vars
2355 self.special_char = '@'
2356
2357 HTMLInputMixin.__init__(self)
2358
2359 self._post_init()
2360
2361 def current_url(self):
2362 url = self.base
2363 if self.classname:
2364 url += self.classname
2365 if self.nodeid:
2366 url += self.nodeid
2367 args = {}
2368 if self.template:
2369 args['@template'] = self.template
2370 return self.indexargs_url(url, args)
2371
2372 def _parse_sort(self, var, name):
2373 """ Parse sort/group options. Append to var
2374 """
2375 fields = []
2376 dirs = []
2377 for special in '@:':
2378 idx = 0
2379 key = '%s%s%d'%(special, name, idx)
2380 while key in self.form:
2381 self.special_char = special
2382 fields.append(self.form.getfirst(key))
2383 dirkey = '%s%sdir%d'%(special, name, idx)
2384 if dirkey in self.form:
2385 dirs.append(self.form.getfirst(dirkey))
2386 else:
2387 dirs.append(None)
2388 idx += 1
2389 key = '%s%s%d'%(special, name, idx)
2390 # backward compatible (and query) URL format
2391 key = special + name
2392 dirkey = key + 'dir'
2393 if key in self.form and not fields:
2394 fields = handleListCGIValue(self.form[key])
2395 if dirkey in self.form:
2396 dirs.append(self.form.getfirst(dirkey))
2397 if fields: # only try other special char if nothing found
2398 break
2399 for f, d in map(None, fields, dirs):
2400 if f.startswith('-'):
2401 var.append(('-', f[1:]))
2402 elif d:
2403 var.append(('-', f))
2404 else:
2405 var.append(('+', f))
2406
2407 def _post_init(self):
2408 """ Set attributes based on self.form
2409 """
2410 # extract the index display information from the form
2411 self.columns = []
2412 for name in ':columns @columns'.split():
2413 if self.form.has_key(name):
2414 self.special_char = name[0]
2415 self.columns = handleListCGIValue(self.form[name])
2416 break
2417 self.show = support.TruthDict(self.columns)
2418
2419 # sorting and grouping
2420 self.sort = []
2421 self.group = []
2422 self._parse_sort(self.sort, 'sort')
2423 self._parse_sort(self.group, 'group')
2424
2425 # filtering
2426 self.filter = []
2427 for name in ':filter @filter'.split():
2428 if self.form.has_key(name):
2429 self.special_char = name[0]
2430 self.filter = handleListCGIValue(self.form[name])
2431
2432 self.filterspec = {}
2433 db = self.client.db
2434 if self.classname is not None:
2435 cls = db.getclass (self.classname)
2436 for name in self.filter:
2437 if not self.form.has_key(name):
2438 continue
2439 prop = cls.get_transitive_prop (name)
2440 fv = self.form[name]
2441 if (isinstance(prop, hyperdb.Link) or
2442 isinstance(prop, hyperdb.Multilink)):
2443 self.filterspec[name] = lookupIds(db, prop,
2444 handleListCGIValue(fv))
2445 else:
2446 if isinstance(fv, type([])):
2447 self.filterspec[name] = [v.value for v in fv]
2448 elif name == 'id':
2449 # special case "id" property
2450 self.filterspec[name] = handleListCGIValue(fv)
2451 else:
2452 self.filterspec[name] = fv.value
2453
2454 # full-text search argument
2455 self.search_text = None
2456 for name in ':search_text @search_text'.split():
2457 if self.form.has_key(name):
2458 self.special_char = name[0]
2459 self.search_text = self.form.getfirst(name)
2460
2461 # pagination - size and start index
2462 # figure batch args
2463 self.pagesize = 50
2464 for name in ':pagesize @pagesize'.split():
2465 if self.form.has_key(name):
2466 self.special_char = name[0]
2467 try:
2468 self.pagesize = int(self.form.getfirst(name))
2469 except ValueError:
2470 # not an integer - ignore
2471 pass
2472
2473 self.startwith = 0
2474 for name in ':startwith @startwith'.split():
2475 if self.form.has_key(name):
2476 self.special_char = name[0]
2477 try:
2478 self.startwith = int(self.form.getfirst(name))
2479 except ValueError:
2480 # not an integer - ignore
2481 pass
2482
2483 # dispname
2484 if self.form.has_key('@dispname'):
2485 self.dispname = self.form.getfirst('@dispname')
2486 else:
2487 self.dispname = None
2488
2489 def updateFromURL(self, url):
2490 """ Parse the URL for query args, and update my attributes using the
2491 values.
2492 """
2493 env = {'QUERY_STRING': url}
2494 self.form = cgi.FieldStorage(environ=env)
2495
2496 self._post_init()
2497
2498 def update(self, kwargs):
2499 """ Update my attributes using the keyword args
2500 """
2501 self.__dict__.update(kwargs)
2502 if kwargs.has_key('columns'):
2503 self.show = support.TruthDict(self.columns)
2504
2505 def description(self):
2506 """ Return a description of the request - handle for the page title.
2507 """
2508 s = [self.client.db.config.TRACKER_NAME]
2509 if self.classname:
2510 if self.client.nodeid:
2511 s.append('- %s%s'%(self.classname, self.client.nodeid))
2512 else:
2513 if self.template == 'item':
2514 s.append('- new %s'%self.classname)
2515 elif self.template == 'index':
2516 s.append('- %s index'%self.classname)
2517 else:
2518 s.append('- %s %s'%(self.classname, self.template))
2519 else:
2520 s.append('- home')
2521 return ' '.join(s)
2522
2523 def __str__(self):
2524 d = {}
2525 d.update(self.__dict__)
2526 f = ''
2527 for k in self.form.keys():
2528 f += '\n %r=%r'%(k,handleListCGIValue(self.form[k]))
2529 d['form'] = f
2530 e = ''
2531 for k,v in self.env.items():
2532 e += '\n %r=%r'%(k, v)
2533 d['env'] = e
2534 return """
2535form: %(form)s
2536base: %(base)r
2537classname: %(classname)r
2538template: %(template)r
2539columns: %(columns)r
2540sort: %(sort)r
2541group: %(group)r
2542filter: %(filter)r
2543search_text: %(search_text)r
2544pagesize: %(pagesize)r
2545startwith: %(startwith)r
2546env: %(env)s
2547"""%d
2548
2549 def indexargs_form(self, columns=1, sort=1, group=1, filter=1,
2550 filterspec=1, search_text=1):
2551 """ return the current index args as form elements """
2552 l = []
2553 sc = self.special_char
2554 def add(k, v):
2555 l.append(self.input(type="hidden", name=k, value=v))
2556 if columns and self.columns:
2557 add(sc+'columns', ','.join(self.columns))
2558 if sort:
2559 val = []
2560 for dir, attr in self.sort:
2561 if dir == '-':
2562 val.append('-'+attr)
2563 else:
2564 val.append(attr)
2565 add(sc+'sort', ','.join (val))
2566 if group:
2567 val = []
2568 for dir, attr in self.group:
2569 if dir == '-':
2570 val.append('-'+attr)
2571 else:
2572 val.append(attr)
2573 add(sc+'group', ','.join (val))
2574 if filter and self.filter:
2575 add(sc+'filter', ','.join(self.filter))
2576 if self.classname and filterspec:
2577 cls = self.client.db.getclass(self.classname)
2578 for k,v in self.filterspec.items():
2579 if type(v) == type([]):
2580 if isinstance(cls.get_transitive_prop(k), hyperdb.String):
2581 add(k, ' '.join(v))
2582 else:
2583 add(k, ','.join(v))
2584 else:
2585 add(k, v)
2586 if search_text and self.search_text:
2587 add(sc+'search_text', self.search_text)
2588 add(sc+'pagesize', self.pagesize)
2589 add(sc+'startwith', self.startwith)
2590 return '\n'.join(l)
2591
2592 def indexargs_url(self, url, args):
2593 """ Embed the current index args in a URL
2594 """
2595 q = urllib.quote
2596 sc = self.special_char
2597 l = ['%s=%s'%(k,v) for k,v in args.items()]
2598
2599 # pull out the special values (prefixed by @ or :)
2600 specials = {}
2601 for key in args.keys():
2602 if key[0] in '@:':
2603 specials[key[1:]] = args[key]
2604
2605 # ok, now handle the specials we received in the request
2606 if self.columns and not specials.has_key('columns'):
2607 l.append(sc+'columns=%s'%(','.join(self.columns)))
2608 if self.sort and not specials.has_key('sort'):
2609 val = []
2610 for dir, attr in self.sort:
2611 if dir == '-':
2612 val.append('-'+attr)
2613 else:
2614 val.append(attr)
2615 l.append(sc+'sort=%s'%(','.join(val)))
2616 if self.group and not specials.has_key('group'):
2617 val = []
2618 for dir, attr in self.group:
2619 if dir == '-':
2620 val.append('-'+attr)
2621 else:
2622 val.append(attr)
2623 l.append(sc+'group=%s'%(','.join(val)))
2624 if self.filter and not specials.has_key('filter'):
2625 l.append(sc+'filter=%s'%(','.join(self.filter)))
2626 if self.search_text and not specials.has_key('search_text'):
2627 l.append(sc+'search_text=%s'%q(self.search_text))
2628 if not specials.has_key('pagesize'):
2629 l.append(sc+'pagesize=%s'%self.pagesize)
2630 if not specials.has_key('startwith'):
2631 l.append(sc+'startwith=%s'%self.startwith)
2632
2633 # finally, the remainder of the filter args in the request
2634 if self.classname and self.filterspec:
2635 cls = self.client.db.getclass(self.classname)
2636 for k,v in self.filterspec.items():
2637 if not args.has_key(k):
2638 if type(v) == type([]):
2639 prop = cls.get_transitive_prop(k)
2640 if k != 'id' and isinstance(prop, hyperdb.String):
2641 l.append('%s=%s'%(k, '%20'.join([q(i) for i in v])))
2642 else:
2643 l.append('%s=%s'%(k, ','.join([q(i) for i in v])))
2644 else:
2645 l.append('%s=%s'%(k, q(v)))
2646 return '%s?%s'%(url, '&'.join(l))
2647 indexargs_href = indexargs_url
2648
2649 def base_javascript(self):
2650 return """
2651<script type="text/javascript">
2652submitted = false;
2653function submit_once() {
2654 if (submitted) {
2655 alert("Your request is being processed.\\nPlease be patient.");
2656 event.returnValue = 0; // work-around for IE
2657 return 0;
2658 }
2659 submitted = true;
2660 return 1;
2661}
2662
2663function help_window(helpurl, width, height) {
2664 HelpWin = window.open('%s' + helpurl, 'RoundupHelpWindow', 'scrollbars=yes,resizable=yes,toolbar=no,height='+height+',width='+width);
2665}
2666</script>
2667"""%self.base
2668
2669 def batch(self):
2670 """ Return a batch object for results from the "current search"
2671 """
2672 check = self._client.db.security.hasPermission
2673 userid = self._client.userid
2674 if not check('Web Access', userid):
2675 return Batch(self.client, [], self.pagesize, self.startwith,
2676 classname=self.classname)
2677
2678 filterspec = self.filterspec
2679 sort = self.sort
2680 group = self.group
2681
2682 # get the list of ids we're batching over
2683 klass = self.client.db.getclass(self.classname)
2684 if self.search_text:
2685 matches = self.client.db.indexer.search(
2686 [w.upper().encode("utf-8", "replace") for w in re.findall(
2687 r'(?u)\b\w{2,25}\b',
2688 unicode(self.search_text, "utf-8", "replace")
2689 )], klass)
2690 else:
2691 matches = None
2692
2693 # filter for visibility
2694 l = [id for id in klass.filter(matches, filterspec, sort, group)
2695 if check('View', userid, self.classname, itemid=id)]
2696
2697 # return the batch object, using IDs only
2698 return Batch(self.client, l, self.pagesize, self.startwith,
2699 classname=self.classname)
2700
2701# extend the standard ZTUtils Batch object to remove dependency on
2702# Acquisition and add a couple of useful methods
2703class Batch(ZTUtils.Batch):
2704 """ Use me to turn a list of items, or item ids of a given class, into a
2705 series of batches.
2706
2707 ========= ========================================================
2708 Parameter Usage
2709 ========= ========================================================
2710 sequence a list of HTMLItems or item ids
2711 classname if sequence is a list of ids, this is the class of item
2712 size how big to make the sequence.
2713 start where to start (0-indexed) in the sequence.
2714 end where to end (0-indexed) in the sequence.
2715 orphan if the next batch would contain less items than this
2716 value, then it is combined with this batch
2717 overlap the number of items shared between adjacent batches
2718 ========= ========================================================
2719
2720 Attributes: Note that the "start" attribute, unlike the
2721 argument, is a 1-based index (I know, lame). "first" is the
2722 0-based index. "length" is the actual number of elements in
2723 the batch.
2724
2725 "sequence_length" is the length of the original, unbatched, sequence.
2726 """
2727 def __init__(self, client, sequence, size, start, end=0, orphan=0,
2728 overlap=0, classname=None):
2729 self.client = client
2730 self.last_index = self.last_item = None
2731 self.current_item = None
2732 self.classname = classname
2733 self.sequence_length = len(sequence)
2734 ZTUtils.Batch.__init__(self, sequence, size, start, end, orphan,
2735 overlap)
2736
2737 # overwrite so we can late-instantiate the HTMLItem instance
2738 def __getitem__(self, index):
2739 if index < 0:
2740 if index + self.end < self.first: raise IndexError, index
2741 return self._sequence[index + self.end]
2742
2743 if index >= self.length:
2744 raise IndexError, index
2745
2746 # move the last_item along - but only if the fetched index changes
2747 # (for some reason, index 0 is fetched twice)
2748 if index != self.last_index:
2749 self.last_item = self.current_item
2750 self.last_index = index
2751
2752 item = self._sequence[index + self.first]
2753 if self.classname:
2754 # map the item ids to instances
2755 item = HTMLItem(self.client, self.classname, item)
2756 self.current_item = item
2757 return item
2758
2759 def propchanged(self, *properties):
2760 """ Detect if one of the properties marked as being a group
2761 property changed in the last iteration fetch
2762 """
2763 # we poke directly at the _value here since MissingValue can screw
2764 # us up and cause Nones to compare strangely
2765 if self.last_item is None:
2766 return 1
2767 for property in properties:
2768 if property == 'id' or isinstance (self.last_item[property], list):
2769 if (str(self.last_item[property]) !=
2770 str(self.current_item[property])):
2771 return 1
2772 else:
2773 if (self.last_item[property]._value !=
2774 self.current_item[property]._value):
2775 return 1
2776 return 0
2777
2778 # override these 'cos we don't have access to acquisition
2779 def previous(self):
2780 if self.start == 1:
2781 return None
2782 return Batch(self.client, self._sequence, self._size,
2783 self.first - self._size + self.overlap, 0, self.orphan,
2784 self.overlap)
2785
2786 def next(self):
2787 try:
2788 self._sequence[self.end]
2789 except IndexError:
2790 return None
2791 return Batch(self.client, self._sequence, self._size,
2792 self.end - self.overlap, 0, self.orphan, self.overlap)
2793
2794class TemplatingUtils:
2795 """ Utilities for templating
2796 """
2797 def __init__(self, client):
2798 self.client = client
2799 def Batch(self, sequence, size, start, end=0, orphan=0, overlap=0):
2800 return Batch(self.client, sequence, size, start, end, orphan,
2801 overlap)
2802
2803 def url_quote(self, url):
2804 """URL-quote the supplied text."""
2805 return urllib.quote(url)
2806
2807 def html_quote(self, html):
2808 """HTML-quote the supplied text."""
2809 return cgi.escape(html)
2810
2811 def __getattr__(self, name):
2812 """Try the tracker's templating_utils."""
2813 if not hasattr(self.client.instance, 'templating_utils'):
2814 # backwards-compatibility
2815 raise AttributeError, name
2816 if not self.client.instance.templating_utils.has_key(name):
2817 raise AttributeError, name
2818 return self.client.instance.templating_utils[name]
2819
2820 def html_calendar(self, request):
2821 """Generate a HTML calendar.
2822
2823 `request` the roundup.request object
2824 - @template : name of the template
2825 - form : name of the form to store back the date
2826 - property : name of the property of the form to store
2827 back the date
2828 - date : current date
2829 - display : when browsing, specifies year and month
2830
2831 html will simply be a table.
2832 """
2833 tz = request.client.db.getUserTimezone()
2834 current_date = date.Date(".").local(tz)
2835 date_str = request.form.getfirst("date", current_date)
2836 display = request.form.getfirst("display", date_str)
2837 template = request.form.getfirst("@template", "calendar")
2838 form = request.form.getfirst("form")
2839 property = request.form.getfirst("property")
2840 curr_date = date.Date(date_str) # to highlight
2841 display = date.Date(display) # to show
2842 day = display.day
2843
2844 # for navigation
2845 date_prev_month = display + date.Interval("-1m")
2846 date_next_month = display + date.Interval("+1m")
2847 date_prev_year = display + date.Interval("-1y")
2848 date_next_year = display + date.Interval("+1y")
2849
2850 res = []
2851
2852 base_link = "%s?@template=%s&property=%s&form=%s&date=%s" % \
2853 (request.classname, template, property, form, curr_date)
2854
2855 # navigation
2856 # month
2857 res.append('<table class="calendar"><tr><td>')
2858 res.append(' <table width="100%" class="calendar_nav"><tr>')
2859 link = "&display=%s"%date_prev_month
2860 res.append(' <td><a href="%s&display=%s">&lt;</a></td>'%(base_link,
2861 date_prev_month))
2862 res.append(' <td>%s</td>'%calendar.month_name[display.month])
2863 res.append(' <td><a href="%s&display=%s">&gt;</a></td>'%(base_link,
2864 date_next_month))
2865 # spacer
2866 res.append(' <td width="100%"></td>')
2867 # year
2868 res.append(' <td><a href="%s&display=%s">&lt;</a></td>'%(base_link,
2869 date_prev_year))
2870 res.append(' <td>%s</td>'%display.year)
2871 res.append(' <td><a href="%s&display=%s">&gt;</a></td>'%(base_link,
2872 date_next_year))
2873 res.append(' </tr></table>')
2874 res.append(' </td></tr>')
2875
2876 # the calendar
2877 res.append(' <tr><td><table class="calendar_display">')
2878 res.append(' <tr class="weekdays">')
2879 for day in calendar.weekheader(3).split():
2880 res.append(' <td>%s</td>'%day)
2881 res.append(' </tr>')
2882 for week in calendar.monthcalendar(display.year, display.month):
2883 res.append(' <tr>')
2884 for day in week:
2885 link = "javascript:form[field].value = '%d-%02d-%02d'; " \
2886 "window.close ();"%(display.year, display.month, day)
2887 if (day == curr_date.day and display.month == curr_date.month
2888 and display.year == curr_date.year):
2889 # highlight
2890 style = "today"
2891 else :
2892 style = ""
2893 if day:
2894 res.append(' <td class="%s"><a href="%s">%s</a></td>'%(
2895 style, link, day))
2896 else :
2897 res.append(' <td></td>')
2898 res.append(' </tr>')
2899 res.append('</table></td></tr></table>')
2900 return "\n".join(res)
2901
2902class MissingValue:
2903 def __init__(self, description, **kwargs):
2904 self.__description = description
2905 for key, value in kwargs.items():
2906 self.__dict__[key] = value
2907
2908 def __call__(self, *args, **kwargs): return MissingValue(self.__description)
2909 def __getattr__(self, name):
2910 # This allows assignments which assume all intermediate steps are Null
2911 # objects if they don't exist yet.
2912 #
2913 # For example (with just 'client' defined):
2914 #
2915 # client.db.config.TRACKER_WEB = 'BASE/'
2916 self.__dict__[name] = MissingValue(self.__description)
2917 return getattr(self, name)
2918
2919 def __getitem__(self, key): return self
2920 def __nonzero__(self): return 0
2921 def __str__(self): return '[%s]'%self.__description
2922 def __repr__(self): return '<MissingValue 0x%x "%s">'%(id(self),
2923 self.__description)
2924 def gettext(self, str): return str
2925 _ = gettext
2926
2927# vim: set et sts=4 sw=4 :