Code

- fix mailgw list of methods -- use getattr so that a derived class will
[roundup.git] / doc / customizing.txt
1 :tocdepth: 2
3 ===================
4 Customising Roundup
5 ===================
7 .. This document borrows from the ZopeBook section on ZPT. The original is at:
8    http://www.zope.org/Documentation/Books/ZopeBook/current/ZPT.stx
10 .. contents::
11    :depth: 1
13 What You Can Do
14 ===============
16 Before you get too far, it's probably worth having a quick read of the Roundup
17 `design documentation`_.
19 Customisation of Roundup can take one of six forms:
21 1. `tracker configuration`_ changes
22 2. database, or `tracker schema`_ changes
23 3. "definition" class `database content`_ changes
24 4. behavioural changes, through detectors_
25 5. `security / access controls`_
26 6. change the `web interface`_
28 The third case is special because it takes two distinctly different forms
29 depending upon whether the tracker has been initialised or not. The other two
30 may be done at any time, before or after tracker initialisation. Yes, this
31 includes adding or removing properties from classes.
34 Trackers in a Nutshell
35 ======================
37 Trackers have the following structure:
39 =================== ========================================================
40 Tracker File        Description
41 =================== ========================================================
42 config.ini          Holds the basic `tracker configuration`_                 
43 schema.py           Holds the `tracker schema`_                              
44 initial_data.py     Holds any data to be entered into the database when the
45                     tracker is initialised.
46 db/                 Holds the tracker's database                             
47 db/files/           Holds the tracker's upload files and messages            
48 db/backend_name     Names the database back-end for the tracker            
49 detectors/          Auditors and reactors for this tracker                   
50 extensions/         Additional web actions and templating utilities.
51 html/               Web interface templates, images and style sheets         
52 lib/                optional common imports for detectors and extensions
53 =================== ======================================================== 
56 Tracker Configuration
57 =====================
59 The ``config.ini`` located in your tracker home contains the basic
60 configuration for the web and e-mail components of roundup's interfaces.
62 Changes to the data captured by your tracker is controlled by the `tracker
63 schema`_.  Some configuration is also performed using permissions - see the 
64 `security / access controls`_ section. For example, to allow users to
65 automatically register through the email interface, you must grant the
66 "Anonymous" Role the "Email Access" Permission.
68 The following is taken from the `Python Library Reference`__ (May 20, 2004)
69 section "ConfigParser -- Configuration file parser":
71  The configuration file consists of sections, led by a "[section]" header
72  and followed by "name = value" entries, with line continuations on a
73  newline with leading whitespace. Note that leading whitespace is removed
74  from values. The optional values can contain format strings which
75  refer to other values in the same section. Lines beginning with "#" or ";"
76  are ignored and may be used to provide comments. 
78  For example::
80    [My Section]
81    foodir = %(dir)s/whatever
82    dir = frob
84  would resolve the "%(dir)s" to the value of "dir" ("frob" in this case)
85  resulting in "foodir" being "frob/whatever".
87 __ http://docs.python.org/lib/module-ConfigParser.html
89 Section **main**
90  database -- ``db``
91   Database directory path. The path may be either absolute or relative
92   to the directory containig this config file.
94  templates -- ``html``
95   Path to the HTML templates directory. The path may be either absolute
96   or relative to the directory containig this config file.
98  static_files -- default *blank*
99   Path to directory holding additional static files available via Web
100   UI.  This directory may contain sitewide images, CSS stylesheets etc.
101   and is searched for these files prior to the TEMPLATES directory
102   specified above.  If this option is not set, all static files are
103   taken from the TEMPLATES directory The path may be either absolute or
104   relative to the directory containig this config file.
106  admin_email -- ``roundup-admin``
107   Email address that roundup will complain to if it runs into trouble. If
108   the email address doesn't contain an ``@`` part, the MAIL_DOMAIN defined
109   below is used.
111  dispatcher_email -- ``roundup-admin``
112   The 'dispatcher' is a role that can get notified of new items to the
113   database. It is used by the ERROR_MESSAGES_TO config setting. If the
114   email address doesn't contain an ``@`` part, the MAIL_DOMAIN defined
115   below is used.
117  email_from_tag -- default *blank*
118   Additional text to include in the "name" part of the From: address used
119   in nosy messages. If the sending user is "Foo Bar", the From: line
120   is usually: ``"Foo Bar" <issue_tracker@tracker.example>``
121   the EMAIL_FROM_TAG goes inside the "Foo Bar" quotes like so:
122   ``"Foo Bar EMAIL_FROM_TAG" <issue_tracker@tracker.example>``
124  new_web_user_roles -- ``User``
125   Roles that a user gets when they register with Web User Interface.
126   This is a comma-separated list of role names (e.g. ``Admin,User``).
128  new_email_user_roles -- ``User``
129   Roles that a user gets when they register with Email Gateway.
130   This is a comma-separated string of role names (e.g. ``Admin,User``).
132  error_messages_to -- ``user``
133   Send error message emails to the ``dispatcher``, ``user``, or ``both``?
134   The dispatcher is configured using the DISPATCHER_EMAIL setting.
135   Allowed values: ``dispatcher``, ``user``, or ``both``
137  html_version -- ``html4``
138   HTML version to generate. The templates are ``html4`` by default.
139   If you wish to make them xhtml, then you'll need to change this
140   var to ``xhtml`` too so all auto-generated HTML is compliant.
141   Allowed values: ``html4``, ``xhtml``
143  timezone -- ``0``
144   Numeric timezone offset used when users do not choose their own
145   in their settings.
147  instant_registration -- ``yes``
148   Register new users instantly, or require confirmation via
149   email?
150   Allowed values: ``yes``, ``no``
152  email_registration_confirmation -- ``yes``
153   Offer registration confirmation by email or only through the web?
154   Allowed values: ``yes``, ``no``
156  indexer_stopwords -- default *blank*
157   Additional stop-words for the full-text indexer specific to
158   your tracker. See the indexer source for the default list of
159   stop-words (e.g. ``A,AND,ARE,AS,AT,BE,BUT,BY, ...``).
161  umask -- ``02``
162   Defines the file creation mode mask.
164 Section **tracker**
165  name -- ``Roundup issue tracker``
166   A descriptive name for your roundup instance.
168  web -- ``http://host.example/demo/``
169   The web address that the tracker is viewable at.
170   This will be included in information sent to users of the tracker.
171   The URL MUST include the cgi-bin part or anything else
172   that is required to get to the home page of the tracker.
173   You MUST include a trailing '/' in the URL.
175  email -- ``issue_tracker``
176   Email address that mail to roundup should go to.
178  language -- default *blank*
179   Default locale name for this tracker. If this option is not set, the
180   language is determined by the environment variable LANGUAGE, LC_ALL,
181   LC_MESSAGES, or LANG, in that order of preference.
183 Section **web**
184  allow_html_file -- ``no``
185   Setting this option enables Roundup to serve uploaded HTML
186   file content *as HTML*. This is a potential security risk
187   and is therefore disabled by default. Set to 'yes' if you
188   trust *all* users uploading content to your tracker.
190  http_auth -- ``yes``
191   Whether to use HTTP Basic Authentication, if present.
192   Roundup will use either the REMOTE_USER or HTTP_AUTHORIZATION
193   variables supplied by your web server (in that order).
194   Set this option to 'no' if you do not wish to use HTTP Basic
195   Authentication in your web interface.
197  use_browser_language -- ``yes``
198   Whether to use HTTP Accept-Language, if present.
199   Browsers send a language-region preference list.
200   It's usually set in the client's browser or in their
201   Operating System.
202   Set this option to 'no' if you want to ignore it.
204  debug -- ``no``
205   Setting this option makes Roundup display error tracebacks
206   in the user's browser rather than emailing them to the
207   tracker admin."),
209 Section **rdbms**
210  Settings in this section are used by Postgresql and MySQL backends only
212  name -- ``roundup``
213   Name of the database to use.
215  host -- ``localhost``
216   Database server host.
218  port -- default *blank*
219   TCP port number of the database server. Postgresql usually resides on
220   port 5432 (if any), for MySQL default port number is 3306. Leave this
221   option empty to use backend default.
223  user -- ``roundup``
224   Database user name that Roundup should use.
226  password -- ``roundup``
227   Database user password.
229  read_default_file -- ``~/.my.cnf``
230   Name of the MySQL defaults file. Only used in MySQL connections.
232  read_default_group -- ``roundup``
233   Name of the group to use in the MySQL defaults file. Only used in
234   MySQL connections.
236 Section **logging**
237  config -- default *blank*
238   Path to configuration file for standard Python logging module. If this
239   option is set, logging configuration is loaded from specified file;
240   options 'filename' and 'level' in this section are ignored. The path may
241   be either absolute or relative to the directory containig this config file.
243  filename -- default *blank*
244   Log file name for minimal logging facility built into Roundup.  If no file
245   name specified, log messages are written on stderr. If above 'config'
246   option is set, this option has no effect. The path may be either absolute
247   or relative to the directory containig this config file.
249  level -- ``ERROR``
250   Minimal severity level of messages written to log file. If above 'config'
251   option is set, this option has no effect.
252   Allowed values: ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR``
254 Section **mail**
255  Outgoing email options. Used for nosy messages, password reset and
256  registration approval requests.
258  domain -- ``localhost``
259   Domain name used for email addresses.
261  host -- default *blank*
262   SMTP mail host that roundup will use to send mail
264  username -- default *blank*
265   SMTP login name. Set this if your mail host requires authenticated access.
266   If username is not empty, password (below) MUST be set!
268  password -- default *blank*
269   SMTP login password.
270   Set this if your mail host requires authenticated access.
272  port -- default *25*
273   SMTP port on mail host.
274   Set this if your mail host runs on a different port.
276  local_hostname -- default *blank*
277   The fully qualified domain name (FQDN) to use during SMTP sessions. If left
278   blank, the underlying SMTP library will attempt to detect your FQDN. If your
279   mail host requires something specific, specify the FQDN to use.
281  tls -- ``no``
282   If your SMTP mail host provides or requires TLS (Transport Layer Security)
283   then you may set this option to 'yes'.
284   Allowed values: ``yes``, ``no``
286  tls_keyfile -- default *blank*
287   If TLS is used, you may set this option to the name of a PEM formatted
288   file that contains your private key. The path may be either absolute or
289   relative to the directory containig this config file.
291  tls_certfile -- default *blank*
292   If TLS is used, you may set this option to the name of a PEM formatted
293   certificate chain file. The path may be either absolute or relative
294   to the directory containig this config file.
296  charset -- utf-8
297   Character set to encode email headers with. We use utf-8 by default, as
298   it's the most flexible. Some mail readers (eg. Eudora) can't cope with
299   that, so you might need to specify a more limited character set
300   (eg. iso-8859-1).
302  debug -- default *blank*
303   Setting this option makes Roundup to write all outgoing email messages
304   to this file *instead* of sending them. This option has the same effect
305   as environment variable SENDMAILDEBUG. Environment variable takes
306   precedence. The path may be either absolute or relative to the directory
307   containig this config file.
309  add_authorinfo -- ``yes``
310   Add a line with author information at top of all messages send by
311   roundup.
313  add_authoremail -- ``yes``
314   Add the mail address of the author to the author information at the
315   top of all messages.  If this is false but add_authorinfo is true,
316   only the name of the actor is added which protects the mail address
317   of the actor from being exposed at mail archives, etc.
319 Section **mailgw**
320  Roundup Mail Gateway options
322  keep_quoted_text -- ``yes``
323   Keep email citations when accepting messages. Setting this to ``no`` strips
324   out "quoted" text from the message. Signatures are also stripped.
325   Allowed values: ``yes``, ``no``
327  leave_body_unchanged -- ``no``
328   Preserve the email body as is - that is, keep the citations *and*
329   signatures.
330   Allowed values: ``yes``, ``no``
332  default_class -- ``issue``
333   Default class to use in the mailgw if one isn't supplied in email subjects.
334   To disable, leave the value blank.
336  language -- default *blank*
337   Default locale name for the tracker mail gateway.  If this option is
338   not set, mail gateway will use the language of the tracker instance.
340  subject_prefix_parsing -- ``strict``
341   Controls the parsing of the [prefix] on subject lines in incoming emails.
342   ``strict`` will return an error to the sender if the [prefix] is not
343   recognised. ``loose`` will attempt to parse the [prefix] but just
344   pass it through as part of the issue title if not recognised. ``none``
345   will always pass any [prefix] through as part of the issue title.
347  subject_suffix_parsing -- ``strict``
348   Controls the parsing of the [suffix] on subject lines in incoming emails.
349   ``strict`` will return an error to the sender if the [suffix] is not
350   recognised. ``loose`` will attempt to parse the [suffix] but just
351   pass it through as part of the issue title if not recognised. ``none``
352   will always pass any [suffix] through as part of the issue title.
354  subject_suffix_delimiters -- ``[]``
355   Defines the brackets used for delimiting the commands suffix in a subject
356   line.
358  subject_content_match -- ``always``
359   Controls matching of the incoming email subject line against issue titles
360   in the case where there is no designator [prefix]. ``never`` turns off
361   matching. ``creation + interval`` or ``activity + interval`` will match
362   an issue for the interval after the issue's creation or last activity.
363   The interval is a standard Roundup interval.
365  subject_updates_title -- ``yes``
366   Update issue title if incoming subject of email is different.
367   Setting this to ``no`` will ignore the title part of
368   the subject of incoming email messages.
370  refwd_re -- ``(\s*\W?\s*(fw|fwd|re|aw|sv|ang)\W)+``
371   Regular expression matching a single reply or forward prefix
372   prepended by the mailer. This is explicitly stripped from the
373   subject during parsing.  Value is Python Regular Expression
374   (UTF8-encoded).
376  origmsg_re -- `` ^[>|\s]*-----\s?Original Message\s?-----$``
377   Regular expression matching start of an original message if quoted
378   the in body.  Value is Python Regular Expression (UTF8-encoded).
380  sign_re -- ``^[>|\s]*-- ?$``
381   Regular expression matching the start of a signature in the message
382   body.  Value is Python Regular Expression (UTF8-encoded).
384  eol_re -- ``[\r\n]+``
385   Regular expression matching end of line.  Value is Python Regular
386   Expression (UTF8-encoded).
388  blankline_re -- ``[\r\n]+\s*[\r\n]+``
389   Regular expression matching a blank line.  Value is Python Regular
390   Expression (UTF8-encoded).
392  ignore_alternatives -- ``no``
393   When parsing incoming mails, roundup uses the first
394   text/plain part it finds. If this part is inside a
395   multipart/alternative, and this option is set, all other
396   parts of the multipart/alternative are ignored. The default
397   is to keep all parts and attach them to the issue.
399 Section **pgp**
400  OpenPGP mail processing options
402  enable -- ``no``
403   Enable PGP processing. Requires pyme.
405  roles -- default *blank*
406   If specified, a comma-separated list of roles to perform PGP
407   processing on. If not specified, it happens for all users.
409  homedir -- default *blank*
410   Location of PGP directory. Defaults to $HOME/.gnupg if not
411   specified.
413 Section **nosy**
414  Nosy messages sending
416  messages_to_author -- ``no``
417   Send nosy messages to the author of the message.
418   Allowed values: ``yes``, ``no``, ``new``
420  signature_position -- ``bottom``
421   Where to place the email signature.
422   Allowed values: ``top``, ``bottom``, ``none``
424  add_author -- ``new``
425   Does the author of a message get placed on the nosy list automatically?
426   If ``new`` is used, then the author will only be added when a message
427   creates a new issue. If ``yes``, then the author will be added on
428   followups too. If ``no``, they're never added to the nosy.
429   Allowed values: ``yes``, ``no``, ``new``
430   
431  add_recipients -- ``new``
432   Do the recipients (``To:``, ``Cc:``) of a message get placed on the nosy
433   list?  If ``new`` is used, then the recipients will only be added when a
434   message creates a new issue. If ``yes``, then the recipients will be added
435   on followups too. If ``no``, they're never added to the nosy.
436   Allowed values: ``yes``, ``no``, ``new``
438  email_sending -- ``single``
439   Controls the email sending from the nosy reactor. If ``multiple`` then
440   a separate email is sent to each recipient. If ``single`` then a single
441   email is sent with each recipient as a CC address.
443  max_attachment_size -- ``2147483647``
444   Attachments larger than the given number of bytes won't be attached
445   to nosy mails. They will be replaced by a link to the tracker's
446   download page for the file.
449 You may generate a new default config file using the ``roundup-admin
450 genconfig`` command.
452 Configuration variables may be referred to in lower or upper case. In code,
453 variables not in the "main" section are referred to using their section and
454 name, so "domain" in the section "mail" becomes MAIL_DOMAIN. The
455 configuration variables available are:
457 Extending the configuration file
458 --------------------------------
460 You can't add new variables to the config.ini file in the tracker home but
461 you can add two new config.ini files:
463 - a config.ini in the ``extensions`` directory will be loaded and attached
464   to the config variable as "ext".
465 - a config.ini in the ``detectors`` directory will be loaded and attached
466   to the config variable as "detectors".
468 For example, the following in ``detectors/config.ini``::
470     [main]
471     qa_recipients = email@example.com
473 is accessible as::
475     db.config.detectors['QA_RECIPIENTS']
477 Note that the name grouping applied to the main configuration file is
478 applied to the extension config files, so if you instead have::
480     [qa]
481     recipients = email@example.com
483 then the above ``db.config.detectors['QA_RECIPIENTS']`` will still work.
486 Tracker Schema
487 ==============
489 .. note::
490    if you modify the schema, you'll most likely need to edit the
491    `web interface`_ HTML template files and `detectors`_ to reflect
492    your changes.
494 A tracker schema defines what data is stored in the tracker's database.
495 Schemas are defined using Python code in the ``schema.py`` module of your
496 tracker.
498 The ``schema.py`` module
499 ------------------------
501 The ``schema.py`` module contains two functions:
503 **open**
504   This function defines what your tracker looks like on the inside, the
505   **schema** of the tracker. It defines the **Classes** and **properties**
506   on each class. It also defines the **security** for those Classes. The
507   next few sections describe how schemas work and what you can do with
508   them.
509 **init**
510   This function is responsible for setting up the initial state of your
511   tracker. It's called exactly once - by the ``roundup-admin initialise``
512   command.  See the start of the section on `database content`_ for more
513   info about how this works.
516 The "classic" schema
517 --------------------
519 The "classic" schema looks like this (see section `setkey(property)`_
520 below for the meaning of ``'setkey'`` -- you may also want to look into
521 the sections `setlabelprop(property)`_ and `setorderprop(property)`_ for
522 specifying (default) labelling and ordering of classes.)::
524     pri = Class(db, "priority", name=String(), order=String())
525     pri.setkey("name")
527     stat = Class(db, "status", name=String(), order=String())
528     stat.setkey("name")
530     keyword = Class(db, "keyword", name=String())
531     keyword.setkey("name")
533     user = Class(db, "user", username=String(), organisation=String(),
534         password=String(), address=String(), realname=String(),
535         phone=String(), alternate_addresses=String(),
536         queries=Multilink('query'), roles=String(), timezone=String())
537     user.setkey("username")
539     msg = FileClass(db, "msg", author=Link("user"), summary=String(),
540         date=Date(), recipients=Multilink("user"),
541         files=Multilink("file"), messageid=String(), inreplyto=String())
543     file = FileClass(db, "file", name=String())
545     issue = IssueClass(db, "issue", keyword=Multilink("keyword"),
546         status=Link("status"), assignedto=Link("user"),
547         priority=Link("priority"))
548     issue.setkey('title')
551 What you can't do to the schema
552 -------------------------------
554 You must never:
556 **Remove the users class**
557   This class is the only *required* class in Roundup.
559 **Remove the "username", "address", "password" or "realname" user properties**
560   Various parts of Roundup require these properties. Don't remove them.
562 **Change the type of a property**
563   Property types must *never* be changed - the database simply doesn't take
564   this kind of action into account. Note that you can't just remove a
565   property and re-add it as a new type either. If you wanted to make the
566   assignedto property a Multilink, you'd need to create a new property
567   assignedto_list and remove the old assignedto property.
570 What you can do to the schema
571 -----------------------------
573 Your schema may be changed at any time before or after the tracker has been
574 initialised (or used). You may:
576 **Add new properties to classes, or add whole new classes**
577   This is painless and easy to do - there are generally no repurcussions
578   from adding new information to a tracker's schema.
580 **Remove properties**
581   Removing properties is a little more tricky - you need to make sure that
582   the property is no longer used in the `web interface`_ *or* by the
583   detectors_.
587 Classes and Properties - creating a new information store
588 ---------------------------------------------------------
590 In the tracker above, we've defined 7 classes of information:
592   priority
593       Defines the possible levels of urgency for issues.
595   status
596       Defines the possible states of processing the issue may be in.
598   keyword
599       Initially empty, will hold keywords useful for searching issues.
601   user
602       Initially holding the "admin" user, will eventually have an entry
603       for all users using roundup.
605   msg
606       Initially empty, will hold all e-mail messages sent to or
607       generated by roundup.
609   file
610       Initially empty, will hold all files attached to issues.
612   issue
613       Initially empty, this is where the issue information is stored.
615 We define the "priority" and "status" classes to allow two things:
616 reduction in the amount of information stored on the issue and more
617 powerful, accurate searching of issues by priority and status. By only
618 requiring a link on the issue (which is stored as a single number) we
619 reduce the chance that someone mis-types a priority or status - or
620 simply makes a new one up.
623 Class and Items
624 ~~~~~~~~~~~~~~~
626 A Class defines a particular class (or type) of data that will be stored
627 in the database. A class comprises one or more properties, which gives
628 the information about the class items.
630 The actual data entered into the database, using ``class.create()``, are
631 called items. They have a special immutable property called ``'id'``. We
632 sometimes refer to this as the *itemid*.
635 Properties
636 ~~~~~~~~~~
638 A Class is comprised of one or more properties of the following types:
640 * String properties are for storing arbitrary-length strings.
641 * Password properties are for storing encoded arbitrary-length strings.
642   The default encoding is defined on the ``roundup.password.Password``
643   class.
644 * Date properties store date-and-time stamps. Their values are Timestamp
645   objects.
646 * Number properties store numeric values.
647 * Boolean properties store on/off, yes/no, true/false values.
648 * A Link property refers to a single other item selected from a
649   specified class. The class is part of the property; the value is an
650   integer, the id of the chosen item.
651 * A Multilink property refers to possibly many items in a specified
652   class. The value is a list of integers.
654 All Classes automatically have a number of properties by default:
656 *creator*
657   Link to the user that created the item.
658 *creation*
659   Date the item was created.
660 *actor*
661   Link to the user that last modified the item.
662 *activity*
663   Date the item was last modified.
666 FileClass
667 ~~~~~~~~~
669 FileClasses save their "content" attribute off in a separate file from
670 the rest of the database. This reduces the number of large entries in
671 the database, which generally makes databases more efficient, and also
672 allows us to use command-line tools to operate on the files. They are
673 stored in the files sub-directory of the ``'db'`` directory in your
674 tracker. FileClasses also have a "type" attribute to store the MIME
675 type of the file.
678 IssueClass
679 ~~~~~~~~~~
681 IssueClasses automatically include the "messages", "files", "nosy", and
682 "superseder" properties.
684 The messages and files properties list the links to the messages and
685 files related to the issue. The nosy property is a list of links to
686 users who wish to be informed of changes to the issue - they get "CC'ed"
687 e-mails when messages are sent to or generated by the issue. The nosy
688 reactor (in the ``'detectors'`` directory) handles this action. The
689 superseder link indicates an issue which has superseded this one.
691 They also have the dynamically generated "creation", "activity" and
692 "creator" properties.
694 The value of the "creation" property is the date when an item was
695 created, and the value of the "activity" property is the date when any
696 property on the item was last edited (equivalently, these are the dates
697 on the first and last records in the item's journal). The "creator"
698 property holds a link to the user that created the issue.
701 setkey(property)
702 ~~~~~~~~~~~~~~~~
704 Select a String property of the class to be the key property. The key
705 property must be unique, and allows references to the items in the class
706 by the content of the key property. That is, we can refer to users by
707 their username: for example, let's say that there's an issue in roundup,
708 issue 23. There's also a user, richard, who happens to be user 2. To
709 assign an issue to him, we could do either of::
711      roundup-admin set issue23 assignedto=2
713 or::
715      roundup-admin set issue23 assignedto=richard
717 Note, the same thing can be done in the web and e-mail interfaces. 
719 setlabelprop(property)
720 ~~~~~~~~~~~~~~~~~~~~~~
722 Select a property of the class to be the label property. The label
723 property is used whereever an item should be uniquely identified, e.g.,
724 when displaying a link to an item. If setlabelprop is not specified for
725 a class, the following values are tried for the label: 
727  * the key of the class (see the `setkey(property)`_ section above)
728  * the "name" property
729  * the "title" property
730  * the first property from the sorted property name list
732 So in most cases you can get away without specifying setlabelprop
733 explicitly.
735 setorderprop(property)
736 ~~~~~~~~~~~~~~~~~~~~~~
738 Select a property of the class to be the order property. The order
739 property is used whenever using a default sort order for the class,
740 e.g., when grouping or sorting class A by a link to class B in the user
741 interface, the order property of class B is used for sorting.  If
742 setorderprop is not specified for a class, the following values are tried
743 for the order property:
745  * the property named "order"
746  * the label property (see `setlabelprop(property)`_ above)
748 So in most cases you can get away without specifying setorderprop
749 explicitly.
751 create(information)
752 ~~~~~~~~~~~~~~~~~~~
754 Create an item in the database. This is generally used to create items
755 in the "definitional" classes like "priority" and "status".
758 A note about ordering
759 ~~~~~~~~~~~~~~~~~~~~~
761 When we sort items in the hyperdb, we use one of a number of methods,
762 depending on the properties being sorted on:
764 1. If it's a String, Number, Date or Interval property, we just sort the
765    scalar value of the property. Strings are sorted case-sensitively.
766 2. If it's a Link property, we sort by either the linked item's "order"
767    property (if it has one) or the linked item's "id".
768 3. Mulitlinks sort similar to #2, but we start with the first Multilink
769    list item, and if they're the same, we sort by the second item, and
770    so on.
772 Note that if an "order" property is defined on a Class that is used for
773 sorting, all items of that Class *must* have a value against the "order"
774 property, or sorting will result in random ordering.
777 Examples of adding to your schema
778 ---------------------------------
780 The Roundup wiki has examples of how schemas can be customised to add
781 new functionality.
784 Detectors - adding behaviour to your tracker
785 ============================================
786 .. _detectors:
788 Detectors are initialised every time you open your tracker database, so
789 you're free to add and remove them any time, even after the database is
790 initialised via the ``roundup-admin initialise`` command.
792 The detectors in your tracker fire *before* (**auditors**) and *after*
793 (**reactors**) changes to the contents of your database. They are Python
794 modules that sit in your tracker's ``detectors`` directory. You will
795 have some installed by default - have a look. You can write new
796 detectors or modify the existing ones. The existing detectors installed
797 for you are:
799 **nosyreaction.py**
800   This provides the automatic nosy list maintenance and email sending.
801   The nosy reactor (``nosyreaction``) fires when new messages are added
802   to issues. The nosy auditor (``updatenosy``) fires when issues are
803   changed, and figures out what changes need to be made to the nosy list
804   (such as adding new authors, etc.)
805 **statusauditor.py**
806   This provides the ``chatty`` auditor which changes the issue status
807   from ``unread`` or ``closed`` to ``chatting`` if new messages appear.
808   It also provides the ``presetunread`` auditor which pre-sets the
809   status to ``unread`` on new items if the status isn't explicitly
810   defined.
811 **messagesummary.py**
812   Generates the ``summary`` property for new messages based on the message
813   content.
814 **userauditor.py**
815   Verifies the content of some of the user fields (email addresses and
816   roles lists).
818 If you don't want this default behaviour, you're completely free to change
819 or remove these detectors.
821 See the detectors section in the `design document`__ for details of the
822 interface for detectors.
824 __ design.html
827 Detector API
828 ------------
830 Auditors are called with the arguments::
832     audit(db, cl, itemid, newdata)
834 where ``db`` is the database, ``cl`` is an instance of Class or
835 IssueClass within the database, and ``newdata`` is a dictionary mapping
836 property names to values.
838 For a ``create()`` operation, the ``itemid`` argument is None and
839 newdata contains all of the initial property values with which the item
840 is about to be created.
842 For a ``set()`` operation, newdata contains only the names and values of
843 properties that are about to be changed.
845 For a ``retire()`` or ``restore()`` operation, newdata is None.
847 Reactors are called with the arguments::
849     react(db, cl, itemid, olddata)
851 where ``db`` is the database, ``cl`` is an instance of Class or
852 IssueClass within the database, and ``olddata`` is a dictionary mapping
853 property names to values.
855 For a ``create()`` operation, the ``itemid`` argument is the id of the
856 newly-created item and ``olddata`` is None.
858 For a ``set()`` operation, ``olddata`` contains the names and previous
859 values of properties that were changed.
861 For a ``retire()`` or ``restore()`` operation, ``itemid`` is the id of
862 the retired or restored item and ``olddata`` is None.
865 Additional Detectors Ready For Use
866 ----------------------------------
868 Sample additional detectors that have been found useful will appear in
869 the ``'detectors'`` directory of the Roundup distribution. If you want
870 to use one, copy it to the ``'detectors'`` of your tracker instance:
872 **newissuecopy.py**
873   This detector sends an email to a team address whenever a new issue is
874   created. The address is hard-coded into the detector, so edit it
875   before you use it (look for the text 'team@team.host') or you'll get
876   email errors!
877 **creator_resolution.py**
878   Catch attempts to set the status to "resolved" - if the assignedto
879   user isn't the creator, then set the status to "confirm-done". Note that
880   "classic" Roundup doesn't have that status, so you'll have to add it. If
881   you don't want to though, it'll just use "in-progress" instead.
882 **email_auditor.py**
883   If a file added to an issue is of type message/rfc822, we tack on the
884   extension .eml.
885   The reason for this is that Microsoft Internet Explorer will not open
886   things with a .eml attachment, as they deem it 'unsafe'. Worse yet,
887   they'll just give you an incomprehensible error message. For more 
888   information, see the detector code - it has a length explanation.
891 Auditor or Reactor?
892 -------------------
894 Generally speaking, the following rules should be observed:
896 **Auditors**
897   Are used for `vetoing creation of or changes to items`_. They might
898   also make automatic changes to item properties.
899 **Reactors**
900   Detect changes in the database and react accordingly. They should avoid
901   making changes to the database where possible, as this could create
902   detector loops.
905 Vetoing creation of or changes to items
906 ---------------------------------------
908 Auditors may raise the ``Reject`` exception to prevent the creation of
909 or changes to items in the database.  The mail gateway, for example, will
910 not attach files or messages to issues when the creation of those files or
911 messages are prevented through the ``Reject`` exception. It'll also not create
912 users if that creation is ``Reject``'ed too.
914 To use, simply add at the top of your auditor::
916    from roundup.exceptions import Reject
918 And then when your rejection criteria have been detected, simply::
920    raise Reject
923 Generating email from Roundup
924 -----------------------------
926 The module ``roundup.mailer`` contains most of the nuts-n-bolts required
927 to generate email messages from Roundup.
929 In addition, the ``IssueClass`` methods ``nosymessage()`` and
930 ``send_message()`` are used to generate nosy messages, and may generate
931 messages which only consist of a change note (ie. the message id parameter
932 is not required - this is referred to as a "System Message" because it
933 comes from "the system" and not a user).
936 Database Content
937 ================
939 .. note::
940    If you modify the content of definitional classes, you'll most
941    likely need to edit the tracker `detectors`_ to reflect your changes.
943 Customisation of the special "definitional" classes (eg. status,
944 priority, resolution, ...) may be done either before or after the
945 tracker is initialised. The actual method of doing so is completely
946 different in each case though, so be careful to use the right one.
948 **Changing content before tracker initialisation**
949     Edit the initial_data.py module in your tracker to alter the items
950     created using the ``create( ... )`` methods.
952 **Changing content after tracker initialisation**
953     As the "admin" user, click on the "class list" link in the web
954     interface to bring up a list of all database classes. Click on the
955     name of the class you wish to change the content of.
957     You may also use the ``roundup-admin`` interface's create, set and
958     retire methods to add, alter or remove items from the classes in
959     question.
961 See "`adding a new field to the classic schema`_" for an example that
962 requires database content changes.
965 Security / Access Controls
966 ==========================
968 A set of Permissions is built into the security module by default:
970 - Create (everything)
971 - Edit (everything)
972 - View (everything)
973 - Register (User class only)
975 These are assigned to the "Admin" Role by default, and allow a user to do
976 anything. Every Class you define in your `tracker schema`_ also gets an
977 Create, Edit and View Permission of its own. The web and email interfaces
978 also define:
980 *Email Access*
981   If defined, the user may use the email interface. Used by default to deny
982   Anonymous users access to the email interface. When granted to the
983   Anonymous user, they will be automatically registered by the email
984   interface (see also the ``new_email_user_roles`` configuration option).
985 *Web Access*
986   If defined, the user may use the web interface. All users are able to see
987   the login form, regardless of this setting (thus enabling logging in).
988 *Web Roles*
989   Controls user access to editing the "roles" property of the "user" class.
990   TODO: deprecate in favour of a property-based control.
992 These are hooked into the default Roles:
994 - Admin (Create, Edit, View and everything; Web Roles)
995 - User (Web Access; Email Access)
996 - Anonymous (Web Access)
998 And finally, the "admin" user gets the "Admin" Role, and the "anonymous"
999 user gets "Anonymous" assigned when the tracker is installed.
1001 For the "User" Role, the "classic" tracker defines:
1003 - Create, Edit and View issue, file, msg, query, keyword 
1004 - View priority, status
1005 - View user
1006 - Edit their own user record
1008 And the "Anonymous" Role is defined as:
1010 - Web interface access
1011 - Register user (for registration)
1012 - View issue, file, msg, query, keyword, priority, status
1014 Put together, these settings appear in the tracker's ``schema.py`` file::
1016     #
1017     # TRACKER SECURITY SETTINGS
1018     #
1019     # See the configuration and customisation document for information
1020     # about security setup.
1022     #
1023     # REGULAR USERS
1024     #
1025     # Give the regular users access to the web and email interface
1026     db.security.addPermissionToRole('User', 'Web Access')
1027     db.security.addPermissionToRole('User', 'Email Access')
1029     # Assign the access and edit Permissions for issue, file and message
1030     # to regular users now
1031     for cl in 'issue', 'file', 'msg', 'query', 'keyword':
1032         db.security.addPermissionToRole('User', 'View', cl)
1033         db.security.addPermissionToRole('User', 'Edit', cl)
1034         db.security.addPermissionToRole('User', 'Create', cl)
1035     for cl in 'priority', 'status':
1036         db.security.addPermissionToRole('User', 'View', cl)
1038     # May users view other user information? Comment these lines out
1039     # if you don't want them to
1040     db.security.addPermissionToRole('User', 'View', 'user')
1042     # Users should be able to edit their own details -- this permission
1043     # is limited to only the situation where the Viewed or Edited item
1044     # is their own.
1045     def own_record(db, userid, itemid):
1046         '''Determine whether the userid matches the item being accessed.'''
1047         return userid == itemid
1048     p = db.security.addPermission(name='View', klass='user', check=own_record,
1049         description="User is allowed to view their own user details")
1050     db.security.addPermissionToRole('User', p)
1051     p = db.security.addPermission(name='Edit', klass='user', check=own_record,
1052         description="User is allowed to edit their own user details")
1053     db.security.addPermissionToRole('User', p)
1055     #
1056     # ANONYMOUS USER PERMISSIONS
1057     #
1058     # Let anonymous users access the web interface. Note that almost all
1059     # trackers will need this Permission. The only situation where it's not
1060     # required is in a tracker that uses an HTTP Basic Authenticated front-end.
1061     db.security.addPermissionToRole('Anonymous', 'Web Access')
1063     # Let anonymous users access the email interface (note that this implies
1064     # that they will be registered automatically, hence they will need the
1065     # "Create" user Permission below)
1066     # This is disabled by default to stop spam from auto-registering users on
1067     # public trackers.
1068     #db.security.addPermissionToRole('Anonymous', 'Email Access')
1070     # Assign the appropriate permissions to the anonymous user's Anonymous
1071     # Role. Choices here are:
1072     # - Allow anonymous users to register
1073     db.security.addPermissionToRole('Anonymous', 'Create', 'user')
1075     # Allow anonymous users access to view issues (and the related, linked
1076     # information)
1077     for cl in 'issue', 'file', 'msg', 'keyword', 'priority', 'status':
1078         db.security.addPermissionToRole('Anonymous', 'View', cl)
1080     # [OPTIONAL]
1081     # Allow anonymous users access to create or edit "issue" items (and the
1082     # related file and message items)
1083     #for cl in 'issue', 'file', 'msg':
1084     #   db.security.addPermissionToRole('Anonymous', 'Create', cl)
1085     #   db.security.addPermissionToRole('Anonymous', 'Edit', cl)
1088 Automatic Permission Checks
1089 ---------------------------
1091 Permissions are automatically checked when information is rendered
1092 through the web. This includes:
1094 1. View checks for properties when being rendered via the ``plain()`` or
1095    similar methods. If the check fails, the text "[hidden]" will be
1096    displayed.
1097 2. Edit checks for properties when the edit field is being rendered via
1098    the ``field()`` or similar methods. If the check fails, the property
1099    will be rendered via the ``plain()`` method (see point 1. for subsequent
1100    checking performed)
1101 3. View checks are performed in index pages for each item being displayed
1102    such that if the user does not have permission, the row is not rendered.
1103 4. View checks are performed at the top of item pages for the Item being
1104    displayed. If the user does not have permission, the text "You are not
1105    allowed to view this page." will be displayed.
1106 5. View checks are performed at the top of index pages for the Class being
1107    displayed. If the user does not have permission, the text "You are not
1108    allowed to view this page." will be displayed.
1111 New User Roles
1112 --------------
1114 New users are assigned the Roles defined in the config file as:
1116 - NEW_WEB_USER_ROLES
1117 - NEW_EMAIL_USER_ROLES
1119 The `users may only edit their issues`_ example shows customisation of
1120 these parameters.
1123 Changing Access Controls
1124 ------------------------
1126 You may alter the configuration variables to change the Role that new
1127 web or email users get, for example to not give them access to the web
1128 interface if they register through email. 
1130 You may use the ``roundup-admin`` "``security``" command to display the
1131 current Role and Permission configuration in your tracker.
1134 Adding a new Permission
1135 ~~~~~~~~~~~~~~~~~~~~~~~
1137 When adding a new Permission, you will need to:
1139 1. add it to your tracker's ``schema.py`` so it is created, using
1140    ``security.addPermission``, for example::
1142     self.security.addPermission(name="View", klass='frozzle',
1143         description="User is allowed to access frozzles")
1145    will set up a new "View" permission on the Class "frozzle".
1146 2. enable it for the Roles that should have it (verify with
1147    "``roundup-admin security``")
1148 3. add it to the relevant HTML interface templates
1149 4. add it to the appropriate xxxPermission methods on in your tracker
1150    interfaces module
1152 The ``addPermission`` method takes a couple of optional parameters:
1154 **properties**
1155   A sequence of property names that are the only properties to apply the
1156   new Permission to (eg. ``... klass='user', properties=('name',
1157   'email') ...``)
1158 **check**
1159   A function to be execute which returns boolean determining whether the
1160   Permission is allowed. The function has the signature ``check(db, userid,
1161   itemid)`` where ``db`` is a handle on the open database, ``userid`` is
1162   the user attempting access and ``itemid`` is the specific item being
1163   accessed.
1165 Example Scenarios
1166 ~~~~~~~~~~~~~~~~~
1168 See the `examples`_ section for longer examples of customisation.
1170 **anonymous access through the e-mail gateway**
1171  Give the "anonymous" user the "Email Access", ("Edit", "issue") and
1172  ("Create", "msg") Permissions but do not not give them the ("Create",
1173  "user") Permission. This means that when an unknown user sends email
1174  into the tracker, they're automatically logged in as "anonymous".
1175  Since they don't have the ("Create", "user") Permission, they won't
1176  be automatically registered, but since "anonymous" has permission to
1177  use the gateway, they'll still be able to submit issues. Note that
1178  the Sender information - their email address - will not be available
1179  - they're *anonymous*.
1181 **automatic registration of users in the e-mail gateway**
1182  By giving the "anonymous" user the ("Register", "user") Permission, any
1183  unidentified user will automatically be registered with the tracker
1184  (with no password, so they won't be able to log in through
1185  the web until an admin sets their password). By default new Roundup
1186  trackers don't allow this as it opens them up to spam. It may be enabled
1187  by uncommenting the appropriate addPermissionToRole in your tracker's
1188  ``schema.py`` file. The new user is given the Roles list defined in the
1189  "new_email_user_roles" config variable. 
1191 **only developers may be assigned issues**
1192  Create a new Permission called "Fixer" for the "issue" class. Create a
1193  new Role "Developer" which has that Permission, and assign that to the
1194  appropriate users. Filter the list of users available in the assignedto
1195  list to include only those users. Enforce the Permission with an
1196  auditor. See the example 
1197  `restricting the list of users that are assignable to a task`_.
1199 **only managers may sign off issues as complete**
1200  Create a new Permission called "Closer" for the "issue" class. Create a
1201  new Role "Manager" which has that Permission, and assign that to the
1202  appropriate users. In your web interface, only display the "resolved"
1203  issue state option when the user has the "Closer" Permissions. Enforce
1204  the Permission with an auditor. This is very similar to the previous
1205  example, except that the web interface check would look like::
1207    <option tal:condition="python:request.user.hasPermission('Closer')"
1208            value="resolved">Resolved</option>
1209  
1210 **don't give web access to users who register through email**
1211  Create a new Role called "Email User" which has all the Permissions of
1212  the normal "User" Role minus the "Web Access" Permission. This will
1213  allow users to send in emails to the tracker, but not access the web
1214  interface.
1216 **let some users edit the details of all users**
1217  Create a new Role called "User Admin" which has the Permission for
1218  editing users::
1220     db.security.addRole(name='User Admin', description='Managing users')
1221     p = db.security.getPermission('Edit', 'user')
1222     db.security.addPermissionToRole('User Admin', p)
1224  and assign the Role to the users who need the permission.
1227 Web Interface
1228 =============
1230 .. contents::
1231    :local:
1233 The web interface is provided by the ``roundup.cgi.client`` module and
1234 is used by ``roundup.cgi``, ``roundup-server`` and ``ZRoundup``
1235 (``ZRoundup``  is broken, until further notice). In all cases, we
1236 determine which tracker is being accessed (the first part of the URL
1237 path inside the scope of the CGI handler) and pass control on to the
1238 ``roundup.cgi.client.Client`` class - which handles the rest of the
1239 access through its ``main()`` method. This means that you can do pretty
1240 much anything you want as a web interface to your tracker.
1244 Repercussions of changing the tracker schema
1245 ---------------------------------------------
1247 If you choose to change the `tracker schema`_ you will need to ensure
1248 the web interface knows about it:
1250 1. Index, item and search pages for the relevant classes may need to
1251    have properties added or removed,
1252 2. The "page" template may require links to be changed, as might the
1253    "home" page's content arguments.
1256 How requests are processed
1257 --------------------------
1259 The basic processing of a web request proceeds as follows:
1261 1. figure out who we are, defaulting to the "anonymous" user
1262 2. figure out what the request is for - we call this the "context"
1263 3. handle any requested action (item edit, search, ...)
1264 4. render the template requested by the context, resulting in HTML
1265    output
1267 In some situations, exceptions occur:
1269 - HTTP Redirect  (generally raised by an action)
1270 - SendFile       (generally raised by ``determine_context``)
1271     here we serve up a FileClass "content" property
1272 - SendStaticFile (generally raised by ``determine_context``)
1273     here we serve up a file from the tracker "html" directory
1274 - Unauthorised   (generally raised by an action)
1275     here the action is cancelled, the request is rendered and an error
1276     message is displayed indicating that permission was not granted for
1277     the action to take place
1278 - NotFound       (raised wherever it needs to be)
1279     this exception percolates up to the CGI interface that called the
1280     client
1283 Determining web context
1284 -----------------------
1286 To determine the "context" of a request, we look at the URL and the
1287 special request variable ``@template``. The URL path after the tracker
1288 identifier is examined. Typical URL paths look like:
1290 1.  ``/tracker/issue``
1291 2.  ``/tracker/issue1``
1292 3.  ``/tracker/@@file/style.css``
1293 4.  ``/cgi-bin/roundup.cgi/tracker/file1``
1294 5.  ``/cgi-bin/roundup.cgi/tracker/file1/kitten.png``
1296 where the "tracker identifier" is "tracker" in the above cases. That means
1297 we're looking at "issue", "issue1", "@@file/style.css", "file1" and
1298 "file1/kitten.png" in the cases above. The path is generally only one
1299 entry long - longer paths are handled differently.
1301 a. if there is no path, then we are in the "home" context. See `the "home"
1302    context`_ below for more information about how it may be used.
1303 b. if the path starts with "@@file" (as in example 3,
1304    "/tracker/@@file/style.css"), then the additional path entry,
1305    "style.css" specifies the filename of a static file we're to serve up
1306    from the tracker TEMPLATES (or STATIC_FILES, if configured) directory.
1307    This is usually the tracker's "html" directory. Raises a SendStaticFile
1308    exception.
1309 c. if there is something in the path (as in example 1, "issue"), it
1310    identifies the tracker class we're to display.
1311 d. if the path is an item designator (as in examples 2 and 4, "issue1"
1312    and "file1"), then we're to display a specific item.
1313 e. if the path starts with an item designator and is longer than one
1314    entry (as in example 5, "file1/kitten.png"), then we're assumed to be
1315    handling an item of a ``FileClass``, and the extra path information
1316    gives the filename that the client is going to label the download
1317    with (i.e. "file1/kitten.png" is nicer to download than "file1").
1318    This raises a ``SendFile`` exception.
1320 Both b. and e. stop before we bother to determine the template we're
1321 going to use. That's because they don't actually use templates.
1323 The template used is specified by the ``@template`` CGI variable, which
1324 defaults to:
1326 - only classname suplied:        "index"
1327 - full item designator supplied: "item"
1330 The "home" Context
1331 ------------------
1333 The "home" context is special because it allows you to add templated
1334 pages to your tracker that don't rely on a class or item (ie. an issues
1335 list or specific issue).
1337 Let's say you wish to add frames to control the layout of your tracker's
1338 interface. You'd probably have:
1340 - A top-level frameset page. This page probably wouldn't be templated, so
1341   it could be served as a static file (see `serving static content`_)
1342 - A sidebar frame that is templated. Let's call this page
1343   "home.navigation.html" in your tracker's "html" directory. To load that
1344   page up, you use the URL:
1346     <tracker url>/home?@template=navigation
1349 Serving static content
1350 ----------------------
1352 See the previous section `determining web context`_ where it describes
1353 ``@@file`` paths.
1356 Performing actions in web requests
1357 ----------------------------------
1359 When a user requests a web page, they may optionally also request for an
1360 action to take place. As described in `how requests are processed`_, the
1361 action is performed before the requested page is generated. Actions are
1362 triggered by using a ``@action`` CGI variable, where the value is one
1363 of:
1365 **login**
1366  Attempt to log a user in.
1368 **logout**
1369  Log the user out - make them "anonymous".
1371 **register**
1372  Attempt to create a new user based on the contents of the form and then
1373  log them in.
1375 **edit**
1376  Perform an edit of an item in the database. There are some `special form
1377  variables`_ you may use.
1379 **new**
1380  Add a new item to the database. You may use the same `special form
1381  variables`_ as in the "edit" action.
1383 **retire**
1384  Retire the item in the database.
1386 **editCSV**
1387  Performs an edit of all of a class' items in one go. See also the
1388  *class*.csv templating method which generates the CSV data to be
1389  edited, and the ``'_generic.index'`` template which uses both of these
1390  features.
1392 **search**
1393  Mangle some of the form variables:
1395  - Set the form ":filter" variable based on the values of the filter
1396    variables - if they're set to anything other than "dontcare" then add
1397    them to :filter.
1399  - Also handle the ":queryname" variable and save off the query to the
1400    user's query list.
1402 Each of the actions is implemented by a corresponding ``*XxxAction*`` (where
1403 "Xxx" is the name of the action) class in the ``roundup.cgi.actions`` module.
1404 These classes are registered with ``roundup.cgi.client.Client``. If you need
1405 to define new actions, you may add them there (see `defining new
1406 web actions`_).
1408 Each action class also has a ``*permission*`` method which determines whether
1409 the action is permissible given the current user. The base permission checks
1410 for each action are:
1412 **login**
1413  Determine whether the user has the "Web Access" Permission.
1414 **logout**
1415  No permission checks are made.
1416 **register**
1417  Determine whether the user has the ("Create", "user") Permission.
1418 **edit**
1419  Determine whether the user has permission to edit this item. If we're
1420  editing the "user" class, users are allowed to edit their own details -
1421  unless they try to edit the "roles" property, which requires the
1422  special Permission "Web Roles".
1423 **new**
1424  Determine whether the user has permission to create this item. No
1425  additional property checks are made. Additionally, new user items may
1426  be created if the user has the ("Create", "user") Permission.
1427 **editCSV**
1428  Determine whether the user has permission to edit this class.
1429 **search**
1430  Determine whether the user has permission to view this class.
1433 Special form variables
1434 ----------------------
1436 Item properties and their values are edited with html FORM
1437 variables and their values. You can:
1439 - Change the value of some property of the current item.
1440 - Create a new item of any class, and edit the new item's
1441   properties,
1442 - Attach newly created items to a multilink property of the
1443   current item.
1444 - Remove items from a multilink property of the current item.
1445 - Specify that some properties are required for the edit
1446   operation to be successful.
1447 - Set up user interface locale.
1449 These operations will only take place if the form action (the
1450 ``@action`` variable) is "edit" or "new".
1452 In the following, <bracketed> values are variable, "@" may be
1453 either ":" or "@", and other text "required" is fixed.
1455 Two special form variables are used to specify user language preferences:
1457 ``@language``
1458   value may be locale name or ``none``. If this variable is set to
1459   locale name, web interface language is changed to given value
1460   (provided that appropriate translation is available), the value
1461   is stored in the browser cookie and will be used for all following
1462   requests.  If value is ``none`` the cookie is removed and the
1463   language is changed to the tracker default, set up in the tracker
1464   configuration or OS environment.
1466 ``@charset``
1467   value may be character set name or ``none``.  Character set name
1468   is stored in the browser cookie and sets output encoding for all
1469   HTML pages generated by Roundup.  If value is ``none`` the cookie
1470   is removed and HTML output is reset to Roundup internal encoding
1471   (UTF-8).
1473 Most properties are specified as form variables:
1475 ``<propname>``
1476   property on the current context item
1478 ``<designator>"@"<propname>``
1479   property on the indicated item (for editing related information)
1481 Designators name a specific item of a class.
1483 ``<classname><N>``
1484     Name an existing item of class <classname>.
1486 ``<classname>"-"<N>``
1487     Name the <N>th new item of class <classname>. If the form
1488     submission is successful, a new item of <classname> is
1489     created. Within the submitted form, a particular
1490     designator of this form always refers to the same new
1491     item.
1493 Once we have determined the "propname", we look at it to see
1494 if it's special:
1496 ``@required``
1497     The associated form value is a comma-separated list of
1498     property names that must be specified when the form is
1499     submitted for the edit operation to succeed.  
1501     When the <designator> is missing, the properties are
1502     for the current context item.  When <designator> is
1503     present, they are for the item specified by
1504     <designator>.
1506     The "@required" specifier must come before any of the
1507     properties it refers to are assigned in the form.
1509 ``@remove@<propname>=id(s)`` or ``@add@<propname>=id(s)``
1510     The "@add@" and "@remove@" edit actions apply only to
1511     Multilink properties.  The form value must be a
1512     comma-separate list of keys for the class specified by
1513     the simple form variable.  The listed items are added
1514     to (respectively, removed from) the specified
1515     property.
1517 ``@link@<propname>=<designator>``
1518     If the edit action is "@link@", the simple form
1519     variable must specify a Link or Multilink property.
1520     The form value is a comma-separated list of
1521     designators.  The item corresponding to each
1522     designator is linked to the property given by simple
1523     form variable.
1525 None of the above (ie. just a simple form value)
1526     The value of the form variable is converted
1527     appropriately, depending on the type of the property.
1529     For a Link('klass') property, the form value is a
1530     single key for 'klass', where the key field is
1531     specified in schema.py.  
1533     For a Multilink('klass') property, the form value is a
1534     comma-separated list of keys for 'klass', where the
1535     key field is specified in schema.py.  
1537     Note that for simple-form-variables specifiying Link
1538     and Multilink properties, the linked-to class must
1539     have a key field.
1541     For a String() property specifying a filename, the
1542     file named by the form value is uploaded. This means we
1543     try to set additional properties "filename" and "type" (if
1544     they are valid for the class).  Otherwise, the property
1545     is set to the form value.
1547     For Date(), Interval(), Boolean(), and Number()
1548     properties, the form value is converted to the
1549     appropriate
1551 Any of the form variables may be prefixed with a classname or
1552 designator.
1554 Two special form values are supported for backwards compatibility:
1556 @note
1557     This is equivalent to::
1559         @link@messages=msg-1
1560         msg-1@content=value
1562     except that in addition, the "author" and "date" properties of
1563     "msg-1" are set to the userid of the submitter, and the current
1564     time, respectively.
1566 @file
1567     This is equivalent to::
1569         @link@files=file-1
1570         file-1@content=value
1572     The String content value is handled as described above for file
1573     uploads.
1575 If both the "@note" and "@file" form variables are
1576 specified, the action::
1578         @link@msg-1@files=file-1
1580 is also performed.
1582 We also check that FileClass items have a "content" property with
1583 actual content, otherwise we remove them from all_props before
1584 returning.
1587 Default templates
1588 -----------------
1590 The default templates are html4 compliant. If you wish to change them to be
1591 xhtml compliant, you'll need to change the ``html_version`` configuration
1592 variable in ``config.ini`` to ``'xhtml'`` instead of ``'html4'``.
1594 Most customisation of the web view can be done by modifying the
1595 templates in the tracker ``'html'`` directory. There are several types
1596 of files in there. The *minimal* template includes:
1598 **page.html**
1599   This template usually defines the overall look of your tracker. When
1600   you view an issue, it appears inside this template. When you view an
1601   index, it also appears inside this template. This template defines a
1602   macro called "icing" which is used by almost all other templates as a
1603   coating for their content, using its "content" slot. It also defines
1604   the "head_title" and "body_title" slots to allow setting of the page
1605   title.
1606 **home.html**
1607   the default page displayed when no other page is indicated by the user
1608 **home.classlist.html**
1609   a special version of the default page that lists the classes in the
1610   tracker
1611 **classname.item.html**
1612   displays an item of the *classname* class
1613 **classname.index.html**
1614   displays a list of *classname* items
1615 **classname.search.html**
1616   displays a search page for *classname* items
1617 **_generic.index.html**
1618   used to display a list of items where there is no
1619   ``*classname*.index`` available
1620 **_generic.help.html**
1621   used to display a "class help" page where there is no
1622   ``*classname*.help``
1623 **user.register.html**
1624   a special page just for the user class, that renders the registration
1625   page
1626 **style.css**
1627   a static file that is served up as-is
1629 The *classic* template has a number of additional templates.
1631 Remember that you can create any template extension you want to,
1632 so if you just want to play around with the templating for new issues,
1633 you can copy the current "issue.item" template to "issue.test", and then
1634 access the test template using the "@template" URL argument::
1636    http://your.tracker.example/tracker/issue?@template=test
1638 and it won't affect your users using the "issue.item" template.
1641 How the templates work
1642 ----------------------
1645 Basic Templating Actions
1646 ~~~~~~~~~~~~~~~~~~~~~~~~
1648 Roundup's templates consist of special attributes on the HTML tags.
1649 These attributes form the `Template Attribute Language`_, or TAL.
1650 The basic TAL commands are:
1652 **tal:define="variable expression; variable expression; ..."**
1653    Define a new variable that is local to this tag and its contents. For
1654    example::
1656       <html tal:define="title request/description">
1657        <head><title tal:content="title"></title></head>
1658       </html>
1660    In this example, the variable "title" is defined as the result of the
1661    expression "request/description". The "tal:content" command inside the
1662    <html> tag may then use the "title" variable.
1664 **tal:condition="expression"**
1665    Only keep this tag and its contents if the expression is true. For
1666    example::
1668      <p tal:condition="python:request.user.hasPermission('View', 'issue')">
1669       Display some issue information.
1670      </p>
1672    In the example, the <p> tag and its contents are only displayed if
1673    the user has the "View" permission for issues. We consider the number
1674    zero, a blank string, an empty list, and the built-in variable
1675    nothing to be false values. Nearly every other value is true,
1676    including non-zero numbers, and strings with anything in them (even
1677    spaces!).
1679 **tal:repeat="variable expression"**
1680    Repeat this tag and its contents for each element of the sequence
1681    that the expression returns, defining a new local variable and a
1682    special "repeat" variable for each element. For example::
1684      <tr tal:repeat="u user/list">
1685       <td tal:content="u/id"></td>
1686       <td tal:content="u/username"></td>
1687       <td tal:content="u/realname"></td>
1688      </tr>
1690    The example would iterate over the sequence of users returned by
1691    "user/list" and define the local variable "u" for each entry. Using
1692    the repeat command creates a new variable called "repeat" which you
1693    may access to gather information about the iteration. See the section
1694    below on `the repeat variable`_.
1696 **tal:replace="expression"**
1697    Replace this tag with the result of the expression. For example::
1699     <span tal:replace="request/user/realname" />
1701    The example would replace the <span> tag and its contents with the
1702    user's realname. If the user's realname was "Bruce", then the
1703    resultant output would be "Bruce".
1705 **tal:content="expression"**
1706    Replace the contents of this tag with the result of the expression.
1707    For example::
1709     <span tal:content="request/user/realname">user's name appears here
1710     </span>
1712    The example would replace the contents of the <span> tag with the
1713    user's realname. If the user's realname was "Bruce" then the
1714    resultant output would be "<span>Bruce</span>".
1716 **tal:attributes="attribute expression; attribute expression; ..."**
1717    Set attributes on this tag to the results of expressions. For
1718    example::
1720      <a tal:attributes="href string:user${request/user/id}">My Details</a>
1722    In the example, the "href" attribute of the <a> tag is set to the
1723    value of the "string:user${request/user/id}" expression, which will
1724    be something like "user123".
1726 **tal:omit-tag="expression"**
1727    Remove this tag (but not its contents) if the expression is true. For
1728    example::
1730       <span tal:omit-tag="python:1">Hello, world!</span>
1732    would result in output of::
1734       Hello, world!
1736 Note that the commands on a given tag are evaulated in the order above,
1737 so *define* comes before *condition*, and so on.
1739 Additionally, you may include tags such as <tal:block>, which are
1740 removed from output. Its content is kept, but the tag itself is not (so
1741 don't go using any "tal:attributes" commands on it). This is useful for
1742 making arbitrary blocks of HTML conditional or repeatable (very handy
1743 for repeating multiple table rows, which would othewise require an
1744 illegal tag placement to effect the repeat).
1746 .. _TAL:
1747 .. _Template Attribute Language:
1748    http://dev.zope.org/Wikis/DevSite/Projects/ZPT/TAL%20Specification%201.4
1751 Templating Expressions
1752 ~~~~~~~~~~~~~~~~~~~~~~
1754 Templating Expressions are covered by `Template Attribute Language
1755 Expression Syntax`_, or TALES. The expressions you may use in the
1756 attribute values may be one of the following forms:
1758 **Path Expressions** - eg. ``item/status/checklist``
1759    These are object attribute / item accesses. Roughly speaking, the
1760    path ``item/status/checklist`` is broken into parts ``item``,
1761    ``status`` and ``checklist``. The ``item`` part is the root of the
1762    expression. We then look for a ``status`` attribute on ``item``, or
1763    failing that, a ``status`` item (as in ``item['status']``). If that
1764    fails, the path expression fails. When we get to the end, the object
1765    we're left with is evaluated to get a string - if it is a method, it
1766    is called; if it is an object, it is stringified. Path expressions
1767    may have an optional ``path:`` prefix, but they are the default
1768    expression type, so it's not necessary.
1770    If an expression evaluates to ``default``, then the expression is
1771    "cancelled" - whatever HTML already exists in the template will
1772    remain (tag content in the case of ``tal:content``, attributes in the
1773    case of ``tal:attributes``).
1775    If an expression evaluates to ``nothing`` then the target of the
1776    expression is removed (tag content in the case of ``tal:content``,
1777    attributes in the case of ``tal:attributes`` and the tag itself in
1778    the case of ``tal:replace``).
1780    If an element in the path may not exist, then you can use the ``|``
1781    operator in the expression to provide an alternative. So, the
1782    expression ``request/form/foo/value | default`` would simply leave
1783    the current HTML in place if the "foo" form variable doesn't exist.
1785    You may use the python function ``path``, as in
1786    ``path("item/status")``, to embed path expressions in Python
1787    expressions.
1789 **String Expressions** - eg. ``string:hello ${user/name}`` 
1790    These expressions are simple string interpolations - though they can
1791    be just plain strings with no interpolation if you want. The
1792    expression in the ``${ ... }`` is just a path expression as above.
1794 **Python Expressions** - eg. ``python: 1+1`` 
1795    These expressions give the full power of Python. All the "root level"
1796    variables are available, so ``python:item.status.checklist()`` would
1797    be equivalent to ``item/status/checklist``, assuming that
1798    ``checklist`` is a method.
1800 Modifiers:
1802 **structure** - eg. ``structure python:msg.content.plain(hyperlink=1)``
1803    The result of expressions are normally *escaped* to be safe for HTML
1804    display (all "<", ">" and "&" are turned into special entities). The
1805    ``structure`` expression modifier turns off this escaping - the
1806    result of the expression is now assumed to be HTML, which is passed
1807    to the web browser for rendering.
1809 **not:** - eg. ``not:python:1=1``
1810    This simply inverts the logical true/false value of another
1811    expression.
1813 .. _TALES:
1814 .. _Template Attribute Language Expression Syntax:
1815    http://dev.zope.org/Wikis/DevSite/Projects/ZPT/TALES%20Specification%201.3
1818 Template Macros
1819 ~~~~~~~~~~~~~~~
1821 Macros are used in Roundup to save us from repeating the same common
1822 page stuctures over and over. The most common (and probably only) macro
1823 you'll use is the "icing" macro defined in the "page" template.
1825 Macros are generated and used inside your templates using special
1826 attributes similar to the `basic templating actions`_. In this case,
1827 though, the attributes belong to the `Macro Expansion Template
1828 Attribute Language`_, or METAL. The macro commands are:
1830 **metal:define-macro="macro name"**
1831   Define that the tag and its contents are now a macro that may be
1832   inserted into other templates using the *use-macro* command. For
1833   example::
1835     <html metal:define-macro="page">
1836      ...
1837     </html>
1839   defines a macro called "page" using the ``<html>`` tag and its
1840   contents. Once defined, macros are stored on the template they're
1841   defined on in the ``macros`` attribute. You can access them later on
1842   through the ``templates`` variable, eg. the most common
1843   ``templates/page/macros/icing`` to access the "page" macro of the
1844   "page" template.
1846 **metal:use-macro="path expression"**
1847   Use a macro, which is identified by the path expression (see above).
1848   This will replace the current tag with the identified macro contents.
1849   For example::
1851    <tal:block metal:use-macro="templates/page/macros/icing">
1852     ...
1853    </tal:block>
1855    will replace the tag and its contents with the "page" macro of the
1856    "page" template.
1858 **metal:define-slot="slot name"** and **metal:fill-slot="slot name"**
1859   To define *dynamic* parts of the macro, you define "slots" which may
1860   be filled when the macro is used with a *use-macro* command. For
1861   example, the ``templates/page/macros/icing`` macro defines a slot like
1862   so::
1864     <title metal:define-slot="head_title">title goes here</title>
1866   In your *use-macro* command, you may now use a *fill-slot* command
1867   like this::
1869     <title metal:fill-slot="head_title">My Title</title>
1871   where the tag that fills the slot completely replaces the one defined
1872   as the slot in the macro.
1874 Note that you may not mix `METAL`_ and `TAL`_ commands on the same tag, but
1875 TAL commands may be used freely inside METAL-using tags (so your
1876 *fill-slots* tags may have all manner of TAL inside them).
1878 .. _METAL:
1879 .. _Macro Expansion Template Attribute Language:
1880    http://dev.zope.org/Wikis/DevSite/Projects/ZPT/METAL%20Specification%201.0
1882 Information available to templates
1883 ----------------------------------
1885 This is implemented by ``roundup.cgi.templating.RoundupPageTemplate``
1887 The following variables are available to templates.
1889 **context**
1890   The current context. This is either None, a `hyperdb class wrapper`_
1891   or a `hyperdb item wrapper`_
1892 **request**
1893   Includes information about the current request, including:
1894    - the current index information (``filterspec``, ``filter`` args,
1895      ``properties``, etc) parsed out of the form. 
1896    - methods for easy filterspec link generation
1897    - "form"
1898      The current CGI form information as a mapping of form argument name
1899      to value (specifically a cgi.FieldStorage)
1900    - "env" the CGI environment variables
1901    - "base" the base URL for this instance
1902    - "user" a HTMLItem instance for the current user
1903    - "language" as determined by the browser or config
1904    - "classname" the current classname (possibly None)
1905    - "template" the current template (suffix, also possibly None)
1906 **config**
1907   This variable holds all the values defined in the tracker config.ini
1908   file (eg. TRACKER_NAME, etc.)
1909 **db**
1910   The current database, used to access arbitrary database items.
1911 **templates**
1912   Access to all the tracker templates by name. Used mainly in
1913   *use-macro* commands.
1914 **utils**
1915   This variable makes available some utility functions like batching.
1916 **nothing**
1917   This is a special variable - if an expression evaluates to this, then
1918   the tag (in the case of a ``tal:replace``), its contents (in the case
1919   of ``tal:content``) or some attributes (in the case of
1920   ``tal:attributes``) will not appear in the the output. So, for
1921   example::
1923     <span tal:attributes="class nothing">Hello, World!</span>
1925   would result in::
1927     <span>Hello, World!</span>
1929 **default**
1930   Also a special variable - if an expression evaluates to this, then the
1931   existing HTML in the template will not be replaced or removed, it will
1932   remain. So::
1934     <span tal:replace="default">Hello, World!</span>
1936   would result in::
1938     <span>Hello, World!</span>
1940 **true**, **false**
1941   Boolean constants that may be used in `templating expressions`_
1942   instead of ``python:1`` and ``python:0``.
1943 **i18n**
1944   Internationalization service, providing two string translation methods:
1946   **gettext** (*message*)
1947     Return the localized translation of message
1948   **ngettext** (*singular*, *plural*, *number*)
1949     Like ``gettext()``, but consider plural forms. If a translation
1950     is found, apply the plural formula to *number*, and return the
1951     resulting message (some languages have more than two plural forms).
1952     If no translation is found, return singular if *number* is 1;
1953     return plural otherwise.
1955     This function requires python2.3; in earlier python versions
1956     may not work as expected.
1958 The context variable
1959 ~~~~~~~~~~~~~~~~~~~~
1961 The *context* variable is one of three things based on the current
1962 context (see `determining web context`_ for how we figure this out):
1964 1. if we're looking at a "home" page, then it's None
1965 2. if we're looking at a specific hyperdb class, it's a
1966    `hyperdb class wrapper`_.
1967 3. if we're looking at a specific hyperdb item, it's a
1968    `hyperdb item wrapper`_.
1970 If the context is not None, we can access the properties of the class or
1971 item. The only real difference between cases 2 and 3 above are:
1973 1. the properties may have a real value behind them, and this will
1974    appear if the property is displayed through ``context/property`` or
1975    ``context/property/field``.
1976 2. the context's "id" property will be a false value in the second case,
1977    but a real, or true value in the third. Thus we can determine whether
1978    we're looking at a real item from the hyperdb by testing
1979    "context/id".
1981 Hyperdb class wrapper
1982 :::::::::::::::::::::
1984 This is implemented by the ``roundup.cgi.templating.HTMLClass``
1985 class.
1987 This wrapper object provides access to a hyperdb class. It is used
1988 primarily in both index view and new item views, but it's also usable
1989 anywhere else that you wish to access information about a class, or the
1990 items of a class, when you don't have a specific item of that class in
1991 mind.
1993 We allow access to properties. There will be no "id" property. The value
1994 accessed through the property will be the current value of the same name
1995 from the CGI form.
1997 There are several methods available on these wrapper objects:
1999 =========== =============================================================
2000 Method      Description
2001 =========== =============================================================
2002 properties  return a `hyperdb property wrapper`_ for all of this class's
2003             properties.
2004 list        lists all of the active (not retired) items in the class.
2005 csv         return the items of this class as a chunk of CSV text.
2006 propnames   lists the names of the properties of this class.
2007 filter      lists of items from this class, filtered and sorted. Two
2008             options are avaible for sorting:
2010             1. by the current *request* filterspec/filter/sort/group args
2011             2. by the "filterspec", "sort" and "group" keyword args.
2012                "filterspec" is ``{propname: value(s)}``. "sort" and
2013                "group" are an optionally empty list ``[(dir, prop)]``
2014                where dir is '+', '-' or None
2015                and prop is a prop name or None.
2017                The propname in filterspec and prop in a sort/group spec
2018                may be transitive, i.e., it may contain properties of
2019                the form link.link.link.name.
2021             eg. All issues with a priority of "1" with messages added in
2022             the last week, sorted by activity date:
2023             ``issue.filter(filterspec={"priority": "1",
2024             'messages.creation' : '.-1w;'}, sort=[('activity', '+')])``
2026 filter_sql  **Only in SQL backends**
2028             Lists the items that match the SQL provided. The SQL is a
2029             complete "select" statement.
2031             The SQL select must include the item id as the first column.
2033             This function **does not** filter out retired items, add
2034             on a where clause "__retired__ <> 1" if you don't want
2035             retired nodes.
2037 classhelp   display a link to a javascript popup containing this class'
2038             "help" template.
2040             This generates a link to a popup window which displays the
2041             properties indicated by "properties" of the class named by
2042             "classname". The "properties" should be a comma-separated list
2043             (eg. 'id,name,description'). Properties defaults to all the
2044             properties of a class (excluding id, creator, created and
2045             activity).
2047             You may optionally override the "label" displayed, the "width",
2048             the "height", the number of items per page ("pagesize") and
2049             the field on which the list is sorted ("sort").
2051             With the "filter" arg it is possible to specify a filter for
2052             which items are supposed to be displayed. It has to be of
2053             the format "<field>=<values>;<field>=<values>;...".
2055             The popup window will be resizable and scrollable.
2057             If the "property" arg is given, it's passed through to the
2058             javascript help_window function. This allows updating of a
2059             property in the calling HTML page.
2061             If the "form" arg is given, it's passed through to the
2062             javascript help_window function - it's the name of the form
2063             the "property" belongs to.
2065 submit      generate a submit button (and action hidden element)
2066 renderWith  render this class with the given template.
2067 history     returns 'New node - no history' :)
2068 is_edit_ok  is the user allowed to Edit the current class?
2069 is_view_ok  is the user allowed to View the current class?
2070 =========== =============================================================
2072 Note that if you have a property of the same name as one of the above
2073 methods, you'll need to access it using a python "item access"
2074 expression. For example::
2076    python:context['list']
2078 will access the "list" property, rather than the list method.
2081 Hyperdb item wrapper
2082 ::::::::::::::::::::
2084 This is implemented by the ``roundup.cgi.templating.HTMLItem``
2085 class.
2087 This wrapper object provides access to a hyperdb item.
2089 We allow access to properties. There will be no "id" property. The value
2090 accessed through the property will be the current value of the same name
2091 from the CGI form.
2093 There are several methods available on these wrapper objects:
2095 =============== ========================================================
2096 Method          Description
2097 =============== ========================================================
2098 submit          generate a submit button (and action hidden element)
2099 journal         return the journal of the current item (**not
2100                 implemented**)
2101 history         render the journal of the current item as HTML
2102 renderQueryForm specific to the "query" class - render the search form
2103                 for the query
2104 hasPermission   specific to the "user" class - determine whether the
2105                 user has a Permission. The signature is::
2107                     hasPermission(self, permission, [classname=],
2108                         [property=], [itemid=])
2110                 where the classname defaults to the current context.
2111 hasRole         specific to the "user" class - determine whether the
2112                 user has a Role. The signature is::
2114                     hasRole(self, rolename)
2116 is_edit_ok      is the user allowed to Edit the current item?
2117 is_view_ok      is the user allowed to View the current item?
2118 is_retired      is the item retired?
2119 download_url    generate a url-quoted link for download of FileClass
2120                 item contents (ie. file<id>/<name>)
2121 copy_url        generate a url-quoted link for creating a copy
2122                 of this item.  By default, the copy will acquire
2123                 all properties of the current item except for
2124                 ``messages`` and ``files``.  This can be overridden
2125                 by passing ``exclude`` argument which contains a list
2126                 (or any iterable) of property names that shall not be
2127                 copied.  Database-driven properties like ``id`` or
2128                 ``activity`` cannot be copied.
2129 =============== ========================================================
2131 Note that if you have a property of the same name as one of the above
2132 methods, you'll need to access it using a python "item access"
2133 expression. For example::
2135    python:context['journal']
2137 will access the "journal" property, rather than the journal method.
2140 Hyperdb property wrapper
2141 ::::::::::::::::::::::::
2143 This is implemented by subclasses of the
2144 ``roundup.cgi.templating.HTMLProperty`` class (``HTMLStringProperty``,
2145 ``HTMLNumberProperty``, and so on).
2147 This wrapper object provides access to a single property of a class. Its
2148 value may be either:
2150 1. if accessed through a `hyperdb item wrapper`_, then it's a value from
2151    the hyperdb
2152 2. if access through a `hyperdb class wrapper`_, then it's a value from
2153    the CGI form
2156 The property wrapper has some useful attributes:
2158 =============== ========================================================
2159 Attribute       Description
2160 =============== ========================================================
2161 _name           the name of the property
2162 _value          the value of the property if any - this is the actual
2163                 value retrieved from the hyperdb for this property
2164 =============== ========================================================
2166 There are several methods available on these wrapper objects:
2168 =========== ================================================================
2169 Method      Description
2170 =========== ================================================================
2171 plain       render a "plain" representation of the property. This method
2172             may take two arguments:
2174             escape
2175              If true, escape the text so it is HTML safe (default: no). The
2176              reason this defaults to off is that text is usually escaped
2177              at a later stage by the TAL commands, unless the "structure"
2178              option is used in the template. The following ``tal:content``
2179              expressions are all equivalent::
2180  
2181               "structure python:msg.content.plain(escape=1)"
2182               "python:msg.content.plain()"
2183               "msg/content/plain"
2184               "msg/content"
2186              Usually you'll only want to use the escape option in a
2187              complex expression.
2189             hyperlink
2190              If true, turn URLs, email addresses and hyperdb item
2191              designators in the text into hyperlinks (default: no). Note
2192              that you'll need to use the "structure" TAL option if you
2193              want to use this ``tal:content`` expression::
2194   
2195               "structure python:msg.content.plain(hyperlink=1)"
2197              The text is automatically HTML-escaped before the hyperlinking
2198              transformation done in the plain() method.
2200 hyperlinked The same as msg.content.plain(hyperlink=1), but nicer::
2202               "structure msg/content/hyperlinked"
2204 field       render an appropriate form edit field for the property - for
2205             most types this is a text entry box, but for Booleans it's a
2206             tri-state yes/no/neither selection. This method may take some
2207             arguments:
2209             size
2210               Sets the width in characters of the edit field
2212             format (Date properties only)
2213               Sets the format of the date in the field - uses the same
2214               format string argument as supplied to the ``pretty`` method
2215               below.
2217             popcal (Date properties only)
2218               Include the Javascript-based popup calendar for date
2219               selection. Defaults to on.
2221 stext       only on String properties - render the value of the property
2222             as StructuredText (requires the StructureText module to be
2223             installed separately)
2224 multiline   only on String properties - render a multiline form edit
2225             field for the property
2226 email       only on String properties - render the value of the property
2227             as an obscured email address
2228 confirm     only on Password properties - render a second form edit field
2229             for the property, used for confirmation that the user typed
2230             the password correctly. Generates a field with name
2231             "name:confirm".
2232 now         only on Date properties - return the current date as a new
2233             property
2234 reldate     only on Date properties - render the interval between the date
2235             and now
2236 local       only on Date properties - return this date as a new property
2237             with some timezone offset, for example::
2238             
2239                 python:context.creation.local(10)
2241             will render the date with a +10 hour offset.
2242 pretty      Date properties - render the date as "dd Mon YYYY" (eg. "19
2243             Mar 2004"). Takes an optional format argument, for example::
2245                 python:context.activity.pretty('%Y-%m-%d')
2247             Will format as "2004-03-19" instead.
2249             Interval properties - render the interval in a pretty
2250             format (eg. "yesterday"). The format arguments are those used
2251             in the standard ``strftime`` call (see the `Python Library
2252             Reference: time module`__)
2253 popcal      Generate a link to a popup calendar which may be used to
2254             edit the date field, for example::
2256               <span tal:replace="structure context/due/popcal" />
2258             you still need to include the ``field`` for the property, so
2259             typically you'd have::
2261               <span tal:replace="structure context/due/field" />
2262               <span tal:replace="structure context/due/popcal" />
2264 menu        only on Link and Multilink properties - render a form select
2265             list for this property. Takes a number of optional arguments
2267             size
2268                is used to limit the length of the list labels
2269             height
2270                is used to set the <select> tag's "size" attribute
2271             showid
2272                includes the item ids in the list labels
2273             additional
2274                lists properties which should be included in the label
2275             sort_on
2276                 indicates the property to sort the list on as (direction,
2277                 (direction, property) where direction is '+' or '-'. A
2278                 single string with the direction prepended may be used.
2279                 For example: ('-', 'order'), '+name'.
2280             value
2281                 gives a default value to preselect in the menu
2283             The remaining keyword arguments are used as conditions for
2284             filtering the items in the list - they're passed as the
2285             "filterspec" argument to a Class.filter() call. For example::
2287              <span tal:replace="structure context/status/menu" />
2289              <span tal:replace="python:context.status.menu(order='+name",
2290                                    value='chatting', 
2291                                    filterspec={'status': '1,2,3,4'}" />
2293 sorted      only on Multilink properties - produce a list of the linked
2294             items sorted by some property, for example::
2295             
2296                 python:context.files.sorted('creation')
2298             Will list the files by upload date.
2299 reverse     only on Multilink properties - produce a list of the linked
2300             items in reverse order
2301 isset       returns True if the property has been set to a value
2302 =========== ================================================================
2304 __ http://docs.python.org/lib/module-time.html
2306 All of the above functions perform checks for permissions required to
2307 display or edit the data they are manipulating. The simplest case is
2308 editing an issue title. Including the expression::
2310    context/title/field
2312 Will present the user with an edit field, if they have edit permission. If
2313 not, then they will be presented with a static display if they have view
2314 permission. If they don't even have view permission, then an error message
2315 is raised, preventing the display of the page, indicating that they don't
2316 have permission to view the information.
2319 The request variable
2320 ~~~~~~~~~~~~~~~~~~~~
2322 This is implemented by the ``roundup.cgi.templating.HTMLRequest``
2323 class.
2325 The request variable is packed with information about the current
2326 request.
2328 .. taken from ``roundup.cgi.templating.HTMLRequest`` docstring
2330 =========== ============================================================
2331 Variable    Holds
2332 =========== ============================================================
2333 form        the CGI form as a cgi.FieldStorage
2334 env         the CGI environment variables
2335 base        the base URL for this tracker
2336 user        a HTMLUser instance for this user
2337 classname   the current classname (possibly None)
2338 template    the current template (suffix, also possibly None)
2339 form        the current CGI form variables in a FieldStorage
2340 =========== ============================================================
2342 **Index page specific variables (indexing arguments)**
2344 =========== ============================================================
2345 Variable    Holds
2346 =========== ============================================================
2347 columns     dictionary of the columns to display in an index page
2348 show        a convenience access to columns - request/show/colname will
2349             be true if the columns should be displayed, false otherwise
2350 sort        index sort columns [(direction, column name)]
2351 group       index grouping properties [(direction, column name)]
2352 filter      properties to filter the index on
2353 filterspec  values to filter the index on (property=value, eg
2354             ``priority=1`` or ``messages.author=42``
2355 search_text text to perform a full-text search on for an index
2356 =========== ============================================================
2358 There are several methods available on the request variable:
2360 =============== ========================================================
2361 Method          Description
2362 =============== ========================================================
2363 description     render a description of the request - handle for the
2364                 page title
2365 indexargs_form  render the current index args as form elements
2366 indexargs_url   render the current index args as a URL
2367 base_javascript render some javascript that is used by other components
2368                 of the templating
2369 batch           run the current index args through a filter and return a
2370                 list of items (see `hyperdb item wrapper`_, and
2371                 `batching`_)
2372 =============== ========================================================
2374 The form variable
2375 :::::::::::::::::
2377 The form variable is a bit special because it's actually a python
2378 FieldStorage object. That means that you have two ways to access its
2379 contents. For example, to look up the CGI form value for the variable
2380 "name", use the path expression::
2382    request/form/name/value
2384 or the python expression::
2386    python:request.form['name'].value
2388 Note the "item" access used in the python case, and also note the
2389 explicit "value" attribute we have to access. That's because the form
2390 variables are stored as MiniFieldStorages. If there's more than one
2391 "name" value in the form, then the above will break since
2392 ``request/form/name`` is actually a *list* of MiniFieldStorages. So it's
2393 best to know beforehand what you're dealing with.
2396 The db variable
2397 ~~~~~~~~~~~~~~~
2399 This is implemented by the ``roundup.cgi.templating.HTMLDatabase``
2400 class.
2402 Allows access to all hyperdb classes as attributes of this variable. If
2403 you want access to the "user" class, for example, you would use::
2405   db/user
2406   python:db.user
2408 Also, the current id of the current user is available as
2409 ``db.getuid()``. This isn't so useful in templates (where you have
2410 ``request/user``), but it can be useful in detectors or interfaces.
2412 The access results in a `hyperdb class wrapper`_.
2415 The templates variable
2416 ~~~~~~~~~~~~~~~~~~~~~~
2418 This is implemented by the ``roundup.cgi.templating.Templates``
2419 class.
2421 This variable doesn't have any useful methods defined. It supports being
2422 used in expressions to access the templates, and consequently the
2423 template macros. You may access the templates using the following path
2424 expression::
2426    templates/name
2428 or the python expression::
2430    templates[name]
2432 where "name" is the name of the template you wish to access. The
2433 template has one useful attribute, namely "macros". To access a specific
2434 macro (called "macro_name"), use the path expression::
2436    templates/name/macros/macro_name
2438 or the python expression::
2440    templates[name].macros[macro_name]
2442 The repeat variable
2443 ~~~~~~~~~~~~~~~~~~~
2445 The repeat variable holds an entry for each active iteration. That is, if
2446 you have a ``tal:repeat="user db/users"`` command, then there will be a
2447 repeat variable entry called "user". This may be accessed as either::
2449     repeat/user
2450     python:repeat['user']
2452 The "user" entry has a number of methods available for information:
2454 =============== =========================================================
2455 Method          Description
2456 =============== =========================================================
2457 first           True if the current item is the first in the sequence.
2458 last            True if the current item is the last in the sequence.
2459 even            True if the current item is an even item in the sequence.
2460 odd             True if the current item is an odd item in the sequence.
2461 number          Current position in the sequence, starting from 1.
2462 letter          Current position in the sequence as a letter, a through
2463                 z, then aa through zz, and so on.
2464 Letter          Same as letter(), except uppercase.
2465 roman           Current position in the sequence as lowercase roman
2466                 numerals.
2467 Roman           Same as roman(), except uppercase.
2468 =============== =========================================================
2471 The utils variable
2472 ~~~~~~~~~~~~~~~~~~
2474 This is implemented by the
2475 ``roundup.cgi.templating.TemplatingUtils`` class, but it may be extended
2476 as described below.
2478 =============== ========================================================
2479 Method          Description
2480 =============== ========================================================
2481 Batch           return a batch object using the supplied list
2482 url_quote       quote some text as safe for a URL (ie. space, %, ...)
2483 html_quote      quote some text as safe in HTML (ie. <, >, ...)
2484 html_calendar   renders an HTML calendar used by the
2485                 ``_generic.calendar.html`` template (itself invoked by
2486                 the popupCalendar DateHTMLProperty method
2487 =============== ========================================================
2489 You may add additional utility methods by writing them in your tracker
2490 ``extensions`` directory and registering them with the templating system
2491 using ``instance.registerUtil`` (see `adding a time log to your issues`_ for
2492 an example of this).
2495 Batching
2496 ::::::::
2498 Use Batch to turn a list of items, or item ids of a given class, into a
2499 series of batches. Its usage is::
2501     python:utils.Batch(sequence, size, start, end=0, orphan=0,
2502     overlap=0)
2504 or, to get the current index batch::
2506     request/batch
2508 The parameters are:
2510 ========= ==============================================================
2511 Parameter  Usage
2512 ========= ==============================================================
2513 sequence  a list of HTMLItems
2514 size      how big to make the sequence.
2515 start     where to start (0-indexed) in the sequence.
2516 end       where to end (0-indexed) in the sequence.
2517 orphan    if the next batch would contain less items than this value,
2518           then it is combined with this batch
2519 overlap   the number of items shared between adjacent batches
2520 ========= ==============================================================
2522 All of the parameters are assigned as attributes on the batch object. In
2523 addition, it has several more attributes:
2525 =============== ========================================================
2526 Attribute       Description
2527 =============== ========================================================
2528 start           indicates the start index of the batch. *Unlike
2529                 the argument, is a 1-based index (I know, lame)*
2530 first           indicates the start index of the batch *as a 0-based
2531                 index*
2532 length          the actual number of elements in the batch
2533 sequence_length the length of the original, unbatched, sequence.
2534 =============== ========================================================
2536 And several methods:
2538 =============== ========================================================
2539 Method          Description
2540 =============== ========================================================
2541 previous        returns a new Batch with the previous batch settings
2542 next            returns a new Batch with the next batch settings
2543 propchanged     detect if the named property changed on the current item
2544                 when compared to the last item
2545 =============== ========================================================
2547 An example of batching::
2549  <table class="otherinfo">
2550   <tr><th colspan="4" class="header">Existing Keywords</th></tr>
2551   <tr tal:define="keywords db/keyword/list"
2552       tal:repeat="start python:range(0, len(keywords), 4)">
2553    <td tal:define="batch python:utils.Batch(keywords, 4, start)"
2554        tal:repeat="keyword batch" tal:content="keyword/name">
2555        keyword here</td>
2556   </tr>
2557  </table>
2559 ... which will produce a table with four columns containing the items of
2560 the "keyword" class (well, their "name" anyway).
2563 Translations
2564 ~~~~~~~~~~~~
2566 Should you wish to enable multiple languages in template content that you
2567 create you'll need to add new locale files in the tracker home under a
2568 ``locale`` directory. Use the instructions in the ``developer's guide`` to
2569 create the locale files.
2572 Displaying Properties
2573 ---------------------
2575 Properties appear in the user interface in three contexts: in indices,
2576 in editors, and as search arguments. For each type of property, there
2577 are several display possibilities. For example, in an index view, a
2578 string property may just be printed as a plain string, but in an editor
2579 view, that property may be displayed in an editable field.
2582 Index Views
2583 -----------
2585 This is one of the class context views. It is also the default view for
2586 classes. The template used is "*classname*.index".
2589 Index View Specifiers
2590 ~~~~~~~~~~~~~~~~~~~~~
2592 An index view specifier (URL fragment) looks like this (whitespace has
2593 been added for clarity)::
2595     /issue?status=unread,in-progress,resolved&
2596         keyword=security,ui&
2597         @group=priority,-status&
2598         @sort=-activity&
2599         @filters=status,keyword&
2600         @columns=title,status,fixer
2602 The index view is determined by two parts of the specifier: the layout
2603 part and the filter part. The layout part consists of the query
2604 parameters that begin with colons, and it determines the way that the
2605 properties of selected items are displayed. The filter part consists of
2606 all the other query parameters, and it determines the criteria by which
2607 items are selected for display. The filter part is interactively
2608 manipulated with the form widgets displayed in the filter section. The
2609 layout part is interactively manipulated by clicking on the column
2610 headings in the table.
2612 The filter part selects the union of the sets of items with values
2613 matching any specified Link properties and the intersection of the sets
2614 of items with values matching any specified Multilink properties.
2616 The example specifies an index of "issue" items. Only items with a
2617 "status" of either "unread" or "in-progress" or "resolved" are
2618 displayed, and only items with "keyword" values including both "security"
2619 and "ui" are displayed. The items are grouped by priority arranged in
2620 ascending order and in descending order by status; and within
2621 groups, sorted by activity, arranged in descending order. The filter
2622 section shows filters for the "status" and "keyword" properties, and the
2623 table includes columns for the "title", "status", and "fixer"
2624 properties.
2626 ============ =============================================================
2627 Argument     Description
2628 ============ =============================================================
2629 @sort        sort by prop name, optionally preceeded with '-' to give
2630              descending or nothing for ascending sorting. Several
2631              properties can be specified delimited with comma.
2632              Internally a search-page using several sort properties may
2633              use @sort0, @sort1 etc. with option @sortdir0, @sortdir1
2634              etc. for the direction of sorting (a non-empty value of
2635              sortdir0 specifies reverse order).
2636 @group       group by prop name, optionally preceeded with '-' or to sort
2637              in descending or nothing for ascending order. Several
2638              properties can be specified delimited with comma.
2639              Internally a search-page using several grouping properties may
2640              use @group0, @group1 etc. with option @groupdir0, @groupdir1
2641              etc. for the direction of grouping (a non-empty value of
2642              groupdir0 specifies reverse order).
2643 @columns     selects the columns that should be displayed. Default is
2644              all.                     
2645 @filter      indicates which properties are being used in filtering.
2646              Default is none.
2647 propname     selects the values the item properties given by propname must
2648              have (very basic search/filter).
2649 @search_text if supplied, performs a full-text search (message bodies,
2650              issue titles, etc)
2651 ============ =============================================================
2654 Searching Views
2655 ---------------
2657 .. note::
2658    if you add a new column to the ``@columns`` form variable potentials
2659    then you will need to add the column to the appropriate `index views`_
2660    template so that it is actually displayed.
2662 This is one of the class context views. The template used is typically
2663 "*classname*.search". The form on this page should have "search" as its
2664 ``@action`` variable. The "search" action:
2666 - sets up additional filtering, as well as performing indexed text
2667   searching
2668 - sets the ``@filter`` variable correctly
2669 - saves the query off if ``@query_name`` is set.
2671 The search page should lay out any fields that you wish to allow the
2672 user to search on. If your schema contains a large number of properties,
2673 you should be wary of making all of those properties available for
2674 searching, as this can cause confusion. If the additional properties are
2675 Strings, consider having their value indexed, and then they will be
2676 searchable using the full text indexed search. This is both faster, and
2677 more useful for the end user.
2679 If the search view does specify the "search" ``@action``, then it may also
2680 provide an additional argument:
2682 ============ =============================================================
2683 Argument     Description
2684 ============ =============================================================
2685 @query_name  if supplied, the index parameters (including @search_text)
2686              will be saved off as a the query item and registered against
2687              the user's queries property. Note that the *classic* template
2688              schema has this ability, but the *minimal* template schema
2689              does not.
2690 ============ =============================================================
2693 Item Views
2694 ----------
2696 The basic view of a hyperdb item is provided by the "*classname*.item"
2697 template. It generally has three sections; an "editor", a "spool" and a
2698 "history" section.
2701 Editor Section
2702 ~~~~~~~~~~~~~~
2704 The editor section is used to manipulate the item - it may be a static
2705 display if the user doesn't have permission to edit the item.
2707 Here's an example of a basic editor template (this is the default
2708 "classic" template issue item edit form - from the "issue.item.html"
2709 template)::
2711  <table class="form">
2712  <tr>
2713   <th>Title</th>
2714   <td colspan="3" tal:content="structure python:context.title.field(size=60)">title</td>
2715  </tr>
2716  
2717  <tr>
2718   <th>Priority</th>
2719   <td tal:content="structure context/priority/menu">priority</td>
2720   <th>Status</th>
2721   <td tal:content="structure context/status/menu">status</td>
2722  </tr>
2723  
2724  <tr>
2725   <th>Superseder</th>
2726   <td>
2727    <span tal:replace="structure python:context.superseder.field(showid=1, size=20)" />
2728    <span tal:replace="structure python:db.issue.classhelp('id,title')" />
2729    <span tal:condition="context/superseder">
2730     <br>View: <span tal:replace="structure python:context.superseder.link(showid=1)" />
2731    </span>
2732   </td>
2733   <th>Nosy List</th>
2734   <td>
2735    <span tal:replace="structure context/nosy/field" />
2736    <span tal:replace="structure python:db.user.classhelp('username,realname,address,phone')" />
2737   </td>
2738  </tr>
2739  
2740  <tr>
2741   <th>Assigned To</th>
2742   <td tal:content="structure context/assignedto/menu">
2743    assignedto menu
2744   </td>
2745   <td>&nbsp;</td>
2746   <td>&nbsp;</td>
2747  </tr>
2748  
2749  <tr>
2750   <th>Change Note</th>
2751   <td colspan="3">
2752    <textarea name=":note" wrap="hard" rows="5" cols="60"></textarea>
2753   </td>
2754  </tr>
2755  
2756  <tr>
2757   <th>File</th>
2758   <td colspan="3"><input type="file" name=":file" size="40"></td>
2759  </tr>
2760  
2761  <tr>
2762   <td>&nbsp;</td>
2763   <td colspan="3" tal:content="structure context/submit">
2764    submit button will go here
2765   </td>
2766  </tr>
2767  </table>
2770 When a change is submitted, the system automatically generates a message
2771 describing the changed properties. As shown in the example, the editor
2772 template can use the ":note" and ":file" fields, which are added to the
2773 standard changenote message generated by Roundup.
2776 Form values
2777 :::::::::::
2779 We have a number of ways to pull properties out of the form in order to
2780 meet the various needs of:
2782 1. editing the current item (perhaps an issue item)
2783 2. editing information related to the current item (eg. messages or
2784    attached files)
2785 3. creating new information to be linked to the current item (eg. time
2786    spent on an issue)
2788 In the following, ``<bracketed>`` values are variable, ":" may be one of
2789 ":" or "@", and other text ("required") is fixed.
2791 Properties are specified as form variables:
2793 ``<propname>``
2794   property on the current context item
2796 ``<designator>:<propname>``
2797   property on the indicated item (for editing related information)
2799 ``<classname>-<N>:<propname>``
2800   property on the Nth new item of classname (generally for creating new
2801   items to attach to the current item)
2803 Once we have determined the "propname", we check to see if it is one of
2804 the special form values:
2806 ``@required``
2807   The named property values must be supplied or a ValueError will be
2808   raised.
2810 ``@remove@<propname>=id(s)``
2811   The ids will be removed from the multilink property.
2813 ``:add:<propname>=id(s)``
2814   The ids will be added to the multilink property.
2816 ``:link:<propname>=<designator>``
2817   Used to add a link to new items created during edit. These are
2818   collected and returned in ``all_links``. This will result in an
2819   additional linking operation (either Link set or Multilink append)
2820   after the edit/create is done using ``all_props`` in ``_editnodes``.
2821   The <propname> on the current item will be set/appended the id of the
2822   newly created item of class <designator> (where <designator> must be
2823   <classname>-<N>).
2825 Any of the form variables may be prefixed with a classname or
2826 designator.
2828 Two special form values are supported for backwards compatibility:
2830 ``:note``
2831   create a message (with content, author and date), linked to the
2832   context item. This is ALWAYS designated "msg-1".
2833 ``:file``
2834   create a file, attached to the current item and any message created by
2835   :note. This is ALWAYS designated "file-1".
2838 Spool Section
2839 ~~~~~~~~~~~~~
2841 The spool section lists related information like the messages and files
2842 of an issue.
2844 TODO
2847 History Section
2848 ~~~~~~~~~~~~~~~
2850 The final section displayed is the history of the item - its database
2851 journal. This is generally generated with the template::
2853  <tal:block tal:replace="structure context/history" />
2855 *To be done:*
2857 *The actual history entries of the item may be accessed for manual
2858 templating through the "journal" method of the item*::
2860  <tal:block tal:repeat="entry context/journal">
2861   a journal entry
2862  </tal:block>
2864 *where each journal entry is an HTMLJournalEntry.*
2867 Defining new web actions
2868 ------------------------
2870 You may define new actions to be triggered by the ``@action`` form variable.
2871 These are added to the tracker ``extensions`` directory and registered
2872 using ``instance.registerAction``.
2874 All the existing Actions are defined in ``roundup.cgi.actions``.
2876 Adding action classes takes three steps; first you `define the new
2877 action class`_, then you `register the action class`_ with the cgi
2878 interface so it may be triggered by the ``@action`` form variable.
2879 Finally you `use the new action`_ in your HTML form.
2881 See "`setting up a "wizard" (or "druid") for controlled adding of
2882 issues`_" for an example.
2885 Define the new action class
2886 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2888 Create a new action class in your tracker's ``extensions`` directory, for
2889 example ``myaction.py``::
2891  from roundup.cgi.actions import Action
2893  class MyAction(Action):
2894      def handle(self):
2895          ''' Perform some action. No return value is required.
2896          '''
2898 The *self.client* attribute is an instance of ``roundup.cgi.client.Client``.
2899 See the docstring of that class for details of what it can do.
2901 The method will typically check the ``self.form`` variable's contents.
2902 It may then:
2904 - add information to ``self.client.ok_message`` or ``self.client.error_message``
2905 - change the ``self.client.template`` variable to alter what the user will see
2906   next
2907 - raise Unauthorised, SendStaticFile, SendFile, NotFound or Redirect
2908   exceptions (import them from roundup.cgi.exceptions)
2911 Register the action class
2912 ~~~~~~~~~~~~~~~~~~~~~~~~~~
2914 The class is now written, but isn't available to the user until you register
2915 it with the following code appended to your ``myaction.py`` file::
2917     def init(instance):
2918         instance.registerAction('myaction', myActionClass)
2920 This maps the action name "myaction" to the action class we defined.
2923 Use the new action
2924 ~~~~~~~~~~~~~~~~~~
2926 In your HTML form, add a hidden form element like so::
2928   <input type="hidden" name="@action" value="myaction">
2930 where "myaction" is the name you registered in the previous step.
2932 Actions may return content to the user
2933 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2935 Actions generally perform some database manipulation and then pass control
2936 on to the rendering of a template in the current context (see `Determining
2937 web context`_ for how that works.) Some actions will want to generate the
2938 actual content returned to the user. Action methods may return their own
2939 content string to be displayed to the user, overriding the templating step.
2940 In this situation, we assume that the content is HTML by default. You may
2941 override the content type indicated to the user by calling ``setHeader``::
2943    self.client.setHeader('Content-Type', 'text/csv')
2945 This example indicates that the value sent back to the user is actually
2946 comma-separated value content (eg. something to be loaded into a
2947 spreadsheet or database).
2950 8-bit character set support in Web interface
2951 --------------------------------------------
2953 The web interface uses UTF-8 default. It may be overridden in both forms
2954 and a browser cookie.
2956 - In forms, use the ``@charset`` variable.
2957 - To use the cookie override, have the ``roundup_charset`` cookie set.
2959 In both cases, the value is a valid charset name (eg. ``utf-8`` or
2960 ``kio8-r``).
2962 Inside Roundup, all strings are stored and processed in utf-8.
2963 Unfortunately, some older browsers do not work properly with
2964 utf-8-encoded pages (e.g. Netscape Navigator 4 displays wrong
2965 characters in form fields).  This version allows one to change
2966 the character set for http transfers.  To do so, you may add
2967 the following code to your ``page.html`` template::
2969  <tal:block define="uri string:${request/base}${request/env/PATH_INFO}">
2970   <a tal:attributes="href python:request.indexargs_url(uri,
2971    {'@charset':'utf-8'})">utf-8</a>
2972   <a tal:attributes="href python:request.indexargs_url(uri,
2973    {'@charset':'koi8-r'})">koi8-r</a>
2974  </tal:block>
2976 (substitute ``koi8-r`` with appropriate charset for your language).
2977 Charset preference is kept in the browser cookie ``roundup_charset``.
2979 ``meta http-equiv`` lines added to the tracker templates in version 0.6.0
2980 should be changed to include actual character set name::
2982  <meta http-equiv="Content-Type"
2983   tal:attributes="content string:text/html;; charset=${request/client/charset}"
2984  />
2986 The charset is also sent in the http header.
2989 Examples
2990 ========
2992 .. contents::
2993    :local:
2994    :depth: 2
2997 Changing what's stored in the database
2998 --------------------------------------
3000 The following examples illustrate ways to change the information stored in
3001 the database.
3004 Adding a new field to the classic schema
3005 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3007 This example shows how to add a simple field (a due date) to the default
3008 classic schema. It does not add any additional behaviour, such as enforcing
3009 the due date, or causing automatic actions to fire if the due date passes.
3011 You add new fields by editing the ``schema.py`` file in you tracker's home.
3012 Schema changes are automatically applied to the database on the next
3013 tracker access (note that roundup-server would need to be restarted as it
3014 caches the schema).
3016 1. Modify the ``schema.py``::
3018     issue = IssueClass(db, "issue", 
3019                     assignedto=Link("user"), keyword=Multilink("keyword"),
3020                     priority=Link("priority"), status=Link("status"),
3021                     due_date=Date())
3023 2. Add an edit field to the ``issue.item.html`` template::
3025     <tr> 
3026      <th>Due Date</th> 
3027      <td tal:content="structure context/due_date/field" /> 
3028     </tr>
3029     
3030    If you want to show only the date part of due_date then do this instead::
3031    
3032     <tr> 
3033      <th>Due Date</th> 
3034      <td tal:content="structure python:context.due_date.field(format='%Y-%m-%d')" /> 
3035     </tr>
3037 3. Add the property to the ``issue.index.html`` page::
3039     (in the heading row)
3040       <th tal:condition="request/show/due_date">Due Date</th>
3041     (in the data row)
3042       <td tal:condition="request/show/due_date" 
3043           tal:content="i/due_date" />
3044           
3045    If you want format control of the display of the due date you can
3046    enter the following in the data row to show only the actual due date::
3047     
3048       <td tal:condition="request/show/due_date" 
3049           tal:content="python:i.due_date.pretty('%Y-%m-%d')">&nbsp;</td>
3051 4. Add the property to the ``issue.search.html`` page::
3053      <tr tal:define="name string:due_date">
3054        <th i18n:translate="">Due Date:</th>
3055        <td metal:use-macro="search_input"></td>
3056        <td metal:use-macro="column_input"></td>
3057        <td metal:use-macro="sort_input"></td>
3058        <td metal:use-macro="group_input"></td>
3059      </tr>
3061 5. If you wish for the due date to appear in the standard views listed
3062    in the sidebar of the web interface then you'll need to add "due_date"
3063    to the columns and columns_showall lists in your ``page.html``::
3064     
3065     columns string:id,activity,due_date,title,creator,status;
3066     columns_showall string:id,activity,due_date,title,creator,assignedto,status;
3068 Adding a new constrained field to the classic schema
3069 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3071 This example shows how to add a new constrained property (i.e. a
3072 selection of distinct values) to your tracker.
3075 Introduction
3076 ::::::::::::
3078 To make the classic schema of Roundup useful as a TODO tracking system
3079 for a group of systems administrators, it needs an extra data field per
3080 issue: a category.
3082 This would let sysadmins quickly list all TODOs in their particular area
3083 of interest without having to do complex queries, and without relying on
3084 the spelling capabilities of other sysadmins (a losing proposition at
3085 best).
3088 Adding a field to the database
3089 ::::::::::::::::::::::::::::::
3091 This is the easiest part of the change. The category would just be a
3092 plain string, nothing fancy. To change what is in the database you need
3093 to add some lines to the ``schema.py`` file of your tracker instance.
3094 Under the comment::
3096     # add any additional database schema configuration here
3098 add::
3100     category = Class(db, "category", name=String())
3101     category.setkey("name")
3103 Here we are setting up a chunk of the database which we are calling
3104 "category". It contains a string, which we are refering to as "name" for
3105 lack of a more imaginative title. (Since "name" is one of the properties
3106 that Roundup looks for on items if you do not set a key for them, it's
3107 probably a good idea to stick with it for new classes if at all
3108 appropriate.) Then we are setting the key of this chunk of the database
3109 to be that "name". This is equivalent to an index for database types.
3110 This also means that there can only be one category with a given name.
3112 Adding the above lines allows us to create categories, but they're not
3113 tied to the issues that we are going to be creating. It's just a list of
3114 categories off on its own, which isn't much use. We need to link it in
3115 with the issues. To do that, find the lines 
3116 in ``schema.py`` which set up the "issue" class, and then add a link to
3117 the category::
3119     issue = IssueClass(db, "issue", ... ,
3120         category=Multilink("category"), ... )
3122 The ``Multilink()`` means that each issue can have many categories. If
3123 you were adding something with a one-to-one relationship to issues (such
3124 as the "assignedto" property), use ``Link()`` instead.
3126 That is all you need to do to change the schema. The rest of the effort
3127 is fiddling around so you can actually use the new category.
3130 Populating the new category class
3131 :::::::::::::::::::::::::::::::::
3133 If you haven't initialised the database with the ``roundup-admin``
3134 "initialise" command, then you can add the following to the tracker
3135 ``initial_data.py`` under the comment::
3137     # add any additional database creation steps here - but only if you
3138     # haven't initialised the database with the admin "initialise" command
3140 Add::
3142      category = db.getclass('category')
3143      category.create(name="scipy")
3144      category.create(name="chaco")
3145      category.create(name="weave")
3147 If the database has already been initalised, then you need to use the
3148 ``roundup-admin`` tool::
3150      % roundup-admin -i <tracker home>
3151      Roundup <version> ready for input.
3152      Type "help" for help.
3153      roundup> create category name=scipy
3154      1
3155      roundup> create category name=chaco
3156      2
3157      roundup> create category name=weave
3158      3
3159      roundup> exit...
3160      There are unsaved changes. Commit them (y/N)? y
3163 Setting up security on the new objects
3164 ::::::::::::::::::::::::::::::::::::::
3166 By default only the admin user can look at and change objects. This
3167 doesn't suit us, as we want any user to be able to create new categories
3168 as required, and obviously everyone needs to be able to view the
3169 categories of issues for it to be useful.
3171 We therefore need to change the security of the category objects. This
3172 is also done in ``schema.py``.
3174 There are currently two loops which set up permissions and then assign
3175 them to various roles. Simply add the new "category" to both lists::
3177     # Assign the access and edit permissions for issue, file and message
3178     # to regular users now
3179     for cl in 'issue', 'file', 'msg', 'category':
3180         p = db.security.getPermission('View', cl)
3181         db.security.addPermissionToRole('User', 'View', cl)
3182         db.security.addPermissionToRole('User', 'Edit', cl)
3183         db.security.addPermissionToRole('User', 'Create', cl)
3185 These lines assign the "View" and "Edit" Permissions to the "User" role,
3186 so that normal users can view and edit "category" objects.
3188 This is all the work that needs to be done for the database. It will
3189 store categories, and let users view and edit them. Now on to the
3190 interface stuff.
3193 Changing the web left hand frame
3194 ::::::::::::::::::::::::::::::::
3196 We need to give the users the ability to create new categories, and the
3197 place to put the link to this functionality is in the left hand function
3198 bar, under the "Issues" area. The file that defines how this area looks
3199 is ``html/page.html``, which is what we are going to be editing next.
3201 If you look at this file you can see that it contains a lot of
3202 "classblock" sections which are chunks of HTML that will be included or
3203 excluded in the output depending on whether the condition in the
3204 classblock is met. We are going to add the category code at the end of
3205 the classblock for the *issue* class::
3207   <p class="classblock"
3208      tal:condition="python:request.user.hasPermission('View', 'category')">
3209    <b>Categories</b><br>
3210    <a tal:condition="python:request.user.hasPermission('Edit', 'category')"
3211       href="category?@template=item">New Category<br></a>
3212   </p>
3214 The first two lines is the classblock definition, which sets up a
3215 condition that only users who have "View" permission for the "category"
3216 object will have this section included in their output. Next comes a
3217 plain "Categories" header in bold. Everyone who can view categories will
3218 get that.
3220 Next comes the link to the editing area of categories. This link will
3221 only appear if the condition - that the user has "Edit" permissions for
3222 the "category" objects - is matched. If they do have permission then
3223 they will get a link to another page which will let the user add new
3224 categories.
3226 Note that if you have permission to *view* but not to *edit* categories,
3227 then all you will see is a "Categories" header with nothing underneath
3228 it. This is obviously not very good interface design, but will do for
3229 now. I just claim that it is so I can add more links in this section
3230 later on. However, to fix the problem you could change the condition in
3231 the classblock statement, so that only users with "Edit" permission
3232 would see the "Categories" stuff.
3235 Setting up a page to edit categories
3236 ::::::::::::::::::::::::::::::::::::
3238 We defined code in the previous section which let users with the
3239 appropriate permissions see a link to a page which would let them edit
3240 conditions. Now we have to write that page.
3242 The link was for the *item* template of the *category* object. This
3243 translates into Roundup looking for a file called ``category.item.html``
3244 in the ``html`` tracker directory. This is the file that we are going to
3245 write now.
3247 First, we add an info tag in a comment which doesn't affect the outcome
3248 of the code at all, but is useful for debugging. If you load a page in a
3249 browser and look at the page source, you can see which sections come
3250 from which files by looking for these comments::
3252     <!-- category.item -->
3254 Next we need to add in the METAL macro stuff so we get the normal page
3255 trappings::
3257  <tal:block metal:use-macro="templates/page/macros/icing">
3258   <title metal:fill-slot="head_title">Category editing</title>
3259   <td class="page-header-top" metal:fill-slot="body_title">
3260    <h2>Category editing</h2>
3261   </td>
3262   <td class="content" metal:fill-slot="content">
3264 Next we need to setup up a standard HTML form, which is the whole
3265 purpose of this file. We link to some handy javascript which sends the
3266 form through only once. This is to stop users hitting the send button
3267 multiple times when they are impatient and thus having the form sent
3268 multiple times::
3270     <form method="POST" onSubmit="return submit_once()"
3271           enctype="multipart/form-data">
3273 Next we define some code which sets up the minimum list of fields that
3274 we require the user to enter. There will be only one field - "name" - so
3275 they better put something in it, otherwise the whole form is pointless::
3277     <input type="hidden" name="@required" value="name">
3279 To get everything to line up properly we will put everything in a table,
3280 and put a nice big header on it so the user has an idea what is
3281 happening::
3283     <table class="form">
3284      <tr><th class="header" colspan="2">Category</th></tr>
3286 Next, we need the field into which the user is going to enter the new
3287 category. The ``context.name.field(size=60)`` bit tells Roundup to
3288 generate a normal HTML field of size 60, and the contents of that field
3289 will be the "name" variable of the current context (namely "category").
3290 The upshot of this is that when the user types something in
3291 to the form, a new category will be created with that name::
3293     <tr>
3294      <th>Name</th>
3295      <td tal:content="structure python:context.name.field(size=60)">
3296      name</td>
3297     </tr>
3299 Then a submit button so that the user can submit the new category::
3301     <tr>
3302      <td>&nbsp;</td>
3303      <td colspan="3" tal:content="structure context/submit">
3304       submit button will go here
3305      </td>
3306     </tr>
3308 Finally we finish off the tags we used at the start to do the METAL
3309 stuff::
3311   </td>
3312  </tal:block>
3314 So putting it all together, and closing the table and form we get::
3316  <!-- category.item -->
3317  <tal:block metal:use-macro="templates/page/macros/icing">
3318   <title metal:fill-slot="head_title">Category editing</title>
3319   <td class="page-header-top" metal:fill-slot="body_title">
3320    <h2>Category editing</h2>
3321   </td>
3322   <td class="content" metal:fill-slot="content">
3323    <form method="POST" onSubmit="return submit_once()"
3324          enctype="multipart/form-data">
3326     <table class="form">
3327      <tr><th class="header" colspan="2">Category</th></tr>
3329      <tr>
3330       <th>Name</th>
3331       <td tal:content="structure python:context.name.field(size=60)">
3332       name</td>
3333      </tr>
3335      <tr>
3336       <td>
3337         &nbsp;
3338         <input type="hidden" name="@required" value="name"> 
3339       </td>
3340       <td colspan="3" tal:content="structure context/submit">
3341        submit button will go here
3342       </td>
3343      </tr>
3344     </table>
3345    </form>
3346   </td>
3347  </tal:block>
3349 This is quite a lot to just ask the user one simple question, but there
3350 is a lot of setup for basically one line (the form line) to do its work.
3351 To add another field to "category" would involve one more line (well,
3352 maybe a few extra to get the formatting correct).
3355 Adding the category to the issue
3356 ::::::::::::::::::::::::::::::::
3358 We now have the ability to create issues to our heart's content, but
3359 that is pointless unless we can assign categories to issues.  Just like
3360 the ``html/category.item.html`` file was used to define how to add a new
3361 category, the ``html/issue.item.html`` is used to define how a new issue
3362 is created.
3364 Just like ``category.issue.html``, this file defines a form which has a
3365 table to lay things out. It doesn't matter where in the table we add new
3366 stuff, it is entirely up to your sense of aesthetics::
3368    <th>Category</th>
3369    <td>
3370     <span tal:replace="structure context/category/field" />
3371     <span tal:replace="structure python:db.category.classhelp('name',
3372                 property='category', width='200')" />
3373    </td>
3375 First, we define a nice header so that the user knows what the next
3376 section is, then the middle line does what we are most interested in.
3377 This ``context/category/field`` gets replaced by a field which contains
3378 the category in the current context (the current context being the new
3379 issue).
3381 The classhelp lines generate a link (labelled "list") to a popup window
3382 which contains the list of currently known categories.
3385 Searching on categories
3386 :::::::::::::::::::::::
3388 Now we can add categories, and create issues with categories. The next
3389 obvious thing that we would like to be able to do, would be to search
3390 for issues based on their category, so that, for example, anyone working
3391 on the web server could look at all issues in the category "Web".
3393 If you look for "Search Issues" in the ``html/page.html`` file, you will
3394 find that it looks something like 
3395 ``<a href="issue?@template=search">Search Issues</a>``. This shows us
3396 that when you click on "Search Issues" it will be looking for a
3397 ``issue.search.html`` file to display. So that is the file that we will
3398 change.
3400 If you look at this file it should begin to seem familiar, although it
3401 does use some new macros. You can add the new category search code anywhere you
3402 like within that form::
3404   <tr tal:define="name string:category;
3405                   db_klass string:category;
3406                   db_content string:name;">
3407     <th>Priority:</th>
3408     <td metal:use-macro="search_select"></td>
3409     <td metal:use-macro="column_input"></td>
3410     <td metal:use-macro="sort_input"></td>
3411     <td metal:use-macro="group_input"></td>
3412   </tr>
3414 The definitions in the ``<tr>`` opening tag are used by the macros:
3416 - ``search_select`` expands to a drop-down box with all categories using
3417   ``db_klass`` and ``db_content``.
3418 - ``column_input`` expands to a checkbox for selecting what columns
3419   should be displayed.
3420 - ``sort_input`` expands to a radio button for selecting what property
3421   should be sorted on.
3422 - ``group_input`` expands to a radio button for selecting what property
3423   should be grouped on.
3425 The category search code above would expand to the following::
3427   <tr>
3428     <th>Category:</th>
3429     <td>
3430       <select name="category">
3431         <option value="">don't care</option>
3432         <option value="">------------</option>      
3433         <option value="1">scipy</option>
3434         <option value="2">chaco</option>
3435         <option value="3">weave</option>
3436       </select>
3437     </td>
3438     <td><input type="checkbox" name=":columns" value="category"></td>
3439     <td><input type="radio" name=":sort0" value="category"></td>
3440     <td><input type="radio" name=":group0" value="category"></td>
3441   </tr>
3443 Adding category to the default view
3444 :::::::::::::::::::::::::::::::::::
3446 We can now add categories, add issues with categories, and search for
3447 issues based on categories. This is everything that we need to do;
3448 however, there is some more icing that we would like. I think the
3449 category of an issue is important enough that it should be displayed by
3450 default when listing all the issues.
3452 Unfortunately, this is a bit less obvious than the previous steps. The
3453 code defining how the issues look is in ``html/issue.index.html``. This
3454 is a large table with a form down at the bottom for redisplaying and so
3455 forth. 
3457 Firstly we need to add an appropriate header to the start of the table::
3459     <th tal:condition="request/show/category">Category</th>
3461 The *condition* part of this statement is to avoid displaying the
3462 Category column if the user has selected not to see it.
3464 The rest of the table is a loop which will go through every issue that
3465 matches the display criteria. The loop variable is "i" - which means
3466 that every issue gets assigned to "i" in turn.
3468 The new part of code to display the category will look like this::
3470     <td tal:condition="request/show/category"
3471         tal:content="i/category"></td>
3473 The condition is the same as above: only display the condition when the
3474 user hasn't asked for it to be hidden. The next part is to set the
3475 content of the cell to be the category part of "i" - the current issue.
3477 Finally we have to edit ``html/page.html`` again. This time, we need to
3478 tell it that when the user clicks on "Unassigned Issues" or "All Issues",
3479 the category column should be included in the resulting list. If you
3480 scroll down the page file, you can see the links with lots of options.
3481 The option that we are interested in is the ``:columns=`` one which
3482 tells roundup which fields of the issue to display. Simply add
3483 "category" to that list and it all should work.
3485 Adding a time log to your issues
3486 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3488 We want to log the dates and amount of time spent working on issues, and
3489 be able to give a summary of the total time spent on a particular issue.
3491 1. Add a new class to your tracker ``schema.py``::
3493     # storage for time logging
3494     timelog = Class(db, "timelog", period=Interval())
3496    Note that we automatically get the date of the time log entry
3497    creation through the standard property "creation".
3499    You will need to grant "Creation" permission to the users who are
3500    allowed to add timelog entries. You may do this with::
3502     db.security.addPermissionToRole('User', 'Create', 'timelog')
3503     db.security.addPermissionToRole('User', 'View', 'timelog')
3505    If users are also able to *edit* timelog entries, then also include::
3507     db.security.addPermissionToRole('User', 'Edit', 'timelog')
3509 2. Link to the new class from your issue class (again, in
3510    ``schema.py``)::
3512     issue = IssueClass(db, "issue", 
3513                     assignedto=Link("user"), keyword=Multilink("keyword"),
3514                     priority=Link("priority"), status=Link("status"),
3515                     times=Multilink("timelog"))
3517    the "times" property is the new link to the "timelog" class.
3519 3. We'll need to let people add in times to the issue, so in the web
3520    interface we'll have a new entry field. This is a special field
3521    because unlike the other fields in the ``issue.item`` template, it
3522    affects a different item (a timelog item) and not the template's
3523    item (an issue). We have a special syntax for form fields that affect
3524    items other than the template default item (see the cgi 
3525    documentation on `special form variables`_). In particular, we add a
3526    field to capture a new timelog item's period::
3528     <tr> 
3529      <th>Time Log</th> 
3530      <td colspan=3><input type="text" name="timelog-1@period" /> 
3531       (enter as '3y 1m 4d 2:40:02' or parts thereof) 
3532      </td> 
3533     </tr> 
3534          
3535    and another hidden field that links that new timelog item (new
3536    because it's marked as having id "-1") to the issue item. It looks
3537    like this::
3539      <input type="hidden" name="@link@times" value="timelog-1" />
3541    On submission, the "-1" timelog item will be created and assigned a
3542    real item id. The "times" property of the issue will have the new id
3543    added to it.
3544    
3545    The full entry will now look like this::
3546    
3547     <tr> 
3548      <th>Time Log</th> 
3549      <td colspan=3><input type="text" name="timelog-1@period" /> 
3550       (enter as '3y 1m 4d 2:40:02' or parts thereof)
3551       <input type="hidden" name="@link@times" value="timelog-1" /> 
3552      </td> 
3553     </tr> 
3554    
3556 4. We want to display a total of the timelog times that have been
3557    accumulated for an issue. To do this, we'll need to actually write
3558    some Python code, since it's beyond the scope of PageTemplates to
3559    perform such calculations. We do this by adding a module ``timespent.py``
3560    to the ``extensions`` directory in our tracker. The contents of this
3561    file is as follows::
3563     from roundup import date
3565     def totalTimeSpent(times):
3566         ''' Call me with a list of timelog items (which have an
3567             Interval "period" property)
3568         '''
3569         total = date.Interval('0d')
3570         for time in times:
3571             total += time.period._value
3572         return total
3574     def init(instance):
3575         instance.registerUtil('totalTimeSpent', totalTimeSpent)
3577    We will now be able to access the ``totalTimeSpent`` function via the
3578    ``utils`` variable in our templates, as shown in the next step.
3580 5. Display the timelog for an issue::
3582      <table class="otherinfo" tal:condition="context/times">
3583       <tr><th colspan="3" class="header">Time Log
3584        <tal:block
3585             tal:replace="python:utils.totalTimeSpent(context.times)" />
3586       </th></tr>
3587       <tr><th>Date</th><th>Period</th><th>Logged By</th></tr>
3588       <tr tal:repeat="time context/times">
3589        <td tal:content="time/creation"></td>
3590        <td tal:content="time/period"></td>
3591        <td tal:content="time/creator"></td>
3592       </tr>
3593      </table>
3595    I put this just above the Messages log in my issue display. Note our
3596    use of the ``totalTimeSpent`` method which will total up the times
3597    for the issue and return a new Interval. That will be automatically
3598    displayed in the template as text like "+ 1y 2:40" (1 year, 2 hours
3599    and 40 minutes).
3601 6. If you're using a persistent web server - ``roundup-server`` or
3602    ``mod_python`` for example - then you'll need to restart that to pick up
3603    the code changes. When that's done, you'll be able to use the new
3604    time logging interface.
3606 An extension of this modification attaches the timelog entries to any
3607 change message entered at the time of the timelog entry:
3609 A. Add a link to the timelog to the msg class in ``schema.py``:
3611     msg = FileClass(db, "msg",
3612                     author=Link("user", do_journal='no'),
3613                     recipients=Multilink("user", do_journal='no'),
3614                     date=Date(),
3615                     summary=String(),
3616                     files=Multilink("file"),
3617                     messageid=String(),
3618                     inreplyto=String(),
3619                     times=Multilink("timelog"))
3621 B. Add a new hidden field that links that new timelog item (new
3622    because it's marked as having id "-1") to the new message.
3623    The link is placed in ``issue.item.html`` in the same section that
3624    handles the timelog entry.
3625    
3626    It looks like this after this addition::
3628     <tr> 
3629      <th>Time Log</th> 
3630      <td colspan=3><input type="text" name="timelog-1@period" /> 
3631       (enter as '3y 1m 4d 2:40:02' or parts thereof)
3632       <input type="hidden" name="@link@times" value="timelog-1" />
3633       <input type="hidden" name="msg-1@link@times" value="timelog-1" /> 
3634      </td> 
3635     </tr> 
3636  
3637    The "times" property of the message will have the new id added to it.
3639 C. Add the timelog listing from step 5. to the ``msg.item.html`` template
3640    so that the timelog entry appears on the message view page. Note that
3641    the call to totalTimeSpent is not used here since there will only be one
3642    single timelog entry for each message.
3643    
3644    I placed it after the Date entry like this::
3645    
3646     <tr>
3647      <th i18n:translate="">Date:</th>
3648      <td tal:content="context/date"></td>
3649     </tr>
3650     </table>
3651     
3652     <table class="otherinfo" tal:condition="context/times">
3653      <tr><th colspan="3" class="header">Time Log</th></tr>
3654      <tr><th>Date</th><th>Period</th><th>Logged By</th></tr>
3655      <tr tal:repeat="time context/times">
3656       <td tal:content="time/creation"></td>
3657       <td tal:content="time/period"></td>
3658       <td tal:content="time/creator"></td>
3659      </tr>
3660     </table>
3661     
3662     <table class="messages">
3665 Tracking different types of issues
3666 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3668 Sometimes you will want to track different types of issues - developer,
3669 customer support, systems, sales leads, etc. A single Roundup tracker is
3670 able to support multiple types of issues. This example demonstrates adding
3671 a system support issue class to a tracker.
3673 1. Figure out what information you're going to want to capture. OK, so
3674    this is obvious, but sometimes it's better to actually sit down for a
3675    while and think about the schema you're going to implement.
3677 2. Add the new issue class to your tracker's ``schema.py``. Just after the
3678    "issue" class definition, add::
3680     # list our systems
3681     system = Class(db, "system", name=String(), order=Number())
3682     system.setkey("name")
3684     # store issues related to those systems
3685     support = IssueClass(db, "support", 
3686                     assignedto=Link("user"), keyword=Multilink("keyword"),
3687                     status=Link("status"), deadline=Date(),
3688                     affects=Multilink("system"))
3690 3. Copy the existing ``issue.*`` (item, search and index) templates in the
3691    tracker's ``html`` to ``support.*``. Edit them so they use the properties
3692    defined in the ``support`` class. Be sure to check for hidden form
3693    variables like "required" to make sure they have the correct set of
3694    required properties.
3696 4. Edit the modules in the ``detectors``, adding lines to their ``init``
3697    functions where appropriate. Look for ``audit`` and ``react`` registrations
3698    on the ``issue`` class, and duplicate them for ``support``.
3700 5. Create a new sidebar box for the new support class. Duplicate the
3701    existing issues one, changing the ``issue`` class name to ``support``.
3703 6. Re-start your tracker and start using the new ``support`` class.
3706 Optionally, you might want to restrict the users able to access this new
3707 class to just the users with a new "SysAdmin" Role. To do this, we add
3708 some security declarations::
3710     db.security.addPermissionToRole('SysAdmin', 'View', 'support')
3711     db.security.addPermissionToRole('SysAdmin', 'Create', 'support')
3712     db.security.addPermissionToRole('SysAdmin', 'Edit', 'support')
3714 You would then (as an "admin" user) edit the details of the appropriate
3715 users, and add "SysAdmin" to their Roles list.
3717 Alternatively, you might want to change the Edit/View permissions granted
3718 for the ``issue`` class so that it's only available to users with the "System"
3719 or "Developer" Role, and then the new class you're adding is available to
3720 all with the "User" Role.
3723 Using External User Databases
3724 -----------------------------
3726 Using an external password validation source
3727 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3729 .. note:: You will need to either have an "admin" user in your external
3730           password source *or* have one of your regular users have
3731           the Admin Role assigned. If you need to assign the Role *after*
3732           making the changes below, you may use the ``roundup-admin``
3733           program to edit a user's details.
3735 We have a centrally-managed password changing system for our users. This
3736 results in a UN*X passwd-style file that we use for verification of
3737 users. Entries in the file consist of ``name:password`` where the
3738 password is encrypted using the standard UN*X ``crypt()`` function (see
3739 the ``crypt`` module in your Python distribution). An example entry
3740 would be::
3742     admin:aamrgyQfDFSHw
3744 Each user of Roundup must still have their information stored in the Roundup
3745 database - we just use the passwd file to check their password. To do this, we
3746 need to override the standard ``verifyPassword`` method defined in
3747 ``roundup.cgi.actions.LoginAction`` and register the new class. The
3748 following is added as ``externalpassword.py`` in the tracker ``extensions``
3749 directory::
3751     import os, crypt
3752     from roundup.cgi.actions import LoginAction    
3754     class ExternalPasswordLoginAction(LoginAction):
3755         def verifyPassword(self, userid, password):
3756             '''Look through the file, line by line, looking for a
3757             name that matches.
3758             '''
3759             # get the user's username
3760             username = self.db.user.get(userid, 'username')
3762             # the passwords are stored in the "passwd.txt" file in the
3763             # tracker home
3764             file = os.path.join(self.db.config.TRACKER_HOME, 'passwd.txt')
3766             # see if we can find a match
3767             for ent in [line.strip().split(':') for line in
3768                                                 open(file).readlines()]:
3769                 if ent[0] == username:
3770                     return crypt.crypt(password, ent[1][:2]) == ent[1]
3772             # user doesn't exist in the file
3773             return 0
3775     def init(instance):
3776         instance.registerAction('login', ExternalPasswordLoginAction)
3778 You should also remove the redundant password fields from the ``user.item``
3779 template.
3782 Using a UN*X passwd file as the user database
3783 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3785 On some systems the primary store of users is the UN*X passwd file. It
3786 holds information on users such as their username, real name, password
3787 and primary user group.
3789 Roundup can use this store as its primary source of user information,
3790 but it needs additional information too - email address(es), roundup
3791 Roles, vacation flags, roundup hyperdb item ids, etc. Also, "retired"
3792 users must still exist in the user database, unlike some passwd files in
3793 which the users are removed when they no longer have access to a system.
3795 To make use of the passwd file, we therefore synchronise between the two
3796 user stores. We also use the passwd file to validate the user logins, as
3797 described in the previous example, `using an external password
3798 validation source`_. We keep the user lists in sync using a fairly
3799 simple script that runs once a day, or several times an hour if more
3800 immediate access is needed. In short, it:
3802 1. parses the passwd file, finding usernames, passwords and real names,
3803 2. compares that list to the current roundup user list:
3805    a. entries no longer in the passwd file are *retired*
3806    b. entries with mismatching real names are *updated*
3807    c. entries only exist in the passwd file are *created*
3809 3. send an email to administrators to let them know what's been done.
3811 The retiring and updating are simple operations, requiring only a call
3812 to ``retire()`` or ``set()``. The creation operation requires more
3813 information though - the user's email address and their Roundup Roles.
3814 We're going to assume that the user's email address is the same as their
3815 login name, so we just append the domain name to that. The Roles are
3816 determined using the passwd group identifier - mapping their UN*X group
3817 to an appropriate set of Roles.
3819 The script to perform all this, broken up into its main components, is
3820 as follows. Firstly, we import the necessary modules and open the
3821 tracker we're to work on::
3823     import sys, os, smtplib
3824     from roundup import instance, date
3826     # open the tracker
3827     tracker_home = sys.argv[1]
3828     tracker = instance.open(tracker_home)
3830 Next we read in the *passwd* file from the tracker home::
3832     # read in the users from the "passwd.txt" file
3833     file = os.path.join(tracker_home, 'passwd.txt')
3834     users = [x.strip().split(':') for x in open(file).readlines()]
3836 Handle special users (those to ignore in the file, and those who don't
3837 appear in the file)::
3839     # users to not keep ever, pre-load with the users I know aren't
3840     # "real" users
3841     ignore = ['ekmmon', 'bfast', 'csrmail']
3843     # users to keep - pre-load with the roundup-specific users
3844     keep = ['comment_pool', 'network_pool', 'admin', 'dev-team',
3845             'cs_pool', 'anonymous', 'system_pool', 'automated']
3847 Now we map the UN*X group numbers to the Roles that users should have::
3849     roles = {
3850      '501': 'User,Tech',  # tech
3851      '502': 'User',       # finance
3852      '503': 'User,CSR',   # customer service reps
3853      '504': 'User',       # sales
3854      '505': 'User',       # marketing
3855     }
3857 Now we do all the work. Note that the body of the script (where we have
3858 the tracker database open) is wrapped in a ``try`` / ``finally`` clause,
3859 so that we always close the database cleanly when we're finished. So, we
3860 now do all the work::
3862     # open the database
3863     db = tracker.open('admin')
3864     try:
3865         # store away messages to send to the tracker admins
3866         msg = []
3868         # loop over the users list read in from the passwd file
3869         for user,passw,uid,gid,real,home,shell in users:
3870             if user in ignore:
3871                 # this user shouldn't appear in our tracker
3872                 continue
3873             keep.append(user)
3874             try:
3875                 # see if the user exists in the tracker
3876                 uid = db.user.lookup(user)
3878                 # yes, they do - now check the real name for correctness
3879                 if real != db.user.get(uid, 'realname'):
3880                     db.user.set(uid, realname=real)
3881                     msg.append('FIX %s - %s'%(user, real))
3882             except KeyError:
3883                 # nope, the user doesn't exist
3884                 db.user.create(username=user, realname=real,
3885                     address='%s@ekit-inc.com'%user, roles=roles[gid])
3886                 msg.append('ADD %s - %s (%s)'%(user, real, roles[gid]))
3888         # now check that all the users in the tracker are also in our
3889         # "keep" list - retire those who aren't
3890         for uid in db.user.list():
3891             user = db.user.get(uid, 'username')
3892             if user not in keep:
3893                 db.user.retire(uid)
3894                 msg.append('RET %s'%user)
3896         # if we did work, then send email to the tracker admins
3897         if msg:
3898             # create the email
3899             msg = '''Subject: %s user database maintenance
3901             %s
3902             '''%(db.config.TRACKER_NAME, '\n'.join(msg))
3904             # send the email
3905             smtp = smtplib.SMTP(db.config.MAILHOST)
3906             addr = db.config.ADMIN_EMAIL
3907             smtp.sendmail(addr, addr, msg)
3909         # now we're done - commit the changes
3910         db.commit()
3911     finally:
3912         # always close the database cleanly
3913         db.close()
3915 And that's it!
3918 Using an LDAP database for user information
3919 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3921 A script that reads users from an LDAP store using
3922 http://python-ldap.sf.net/ and then compares the list to the users in the
3923 roundup user database would be pretty easy to write. You'd then have it run
3924 once an hour / day (or on demand if you can work that into your LDAP store
3925 workflow). See the example `Using a UN*X passwd file as the user database`_
3926 for more information about doing this.
3928 To authenticate off the LDAP store (rather than using the passwords in the
3929 Roundup user database) you'd use the same python-ldap module inside an
3930 extension to the cgi interface. You'd do this by overriding the method called
3931 ``verifyPassword`` on the ``LoginAction`` class in your tracker's
3932 ``extensions`` directory (see `using an external password validation
3933 source`_). The method is implemented by default as::
3935     def verifyPassword(self, userid, password):
3936         ''' Verify the password that the user has supplied
3937         '''
3938         stored = self.db.user.get(self.userid, 'password')
3939         if password == stored:
3940             return 1
3941         if not password and not stored:
3942             return 1
3943         return 0
3945 So you could reimplement this as something like::
3947     def verifyPassword(self, userid, password):
3948         ''' Verify the password that the user has supplied
3949         '''
3950         # look up some unique LDAP information about the user
3951         username = self.db.user.get(self.userid, 'username')
3952         # now verify the password supplied against the LDAP store
3955 Changes to Tracker Behaviour
3956 ----------------------------
3958 Preventing SPAM
3959 ~~~~~~~~~~~~~~~
3961 The following detector code may be installed in your tracker's
3962 ``detectors`` directory. It will block any messages being created that
3963 have HTML attachments (a very common vector for spam and phishing)
3964 and any messages that have more than 2 HTTP URLs in them. Just copy
3965 the following into ``detectors/anti_spam.py`` in your tracker::
3967     from roundup.exceptions import Reject
3969     def reject_html(db, cl, nodeid, newvalues):
3970         if newvalues['type'] == 'text/html':
3971         raise Reject, 'not allowed'
3973     def reject_manylinks(db, cl, nodeid, newvalues):
3974         content = newvalues['content']
3975         if content.count('http://') > 2:
3976         raise Reject, 'not allowed'
3978     def init(db):
3979         db.file.audit('create', reject_html)
3980         db.msg.audit('create', reject_manylinks)
3982 You may also wish to block image attachments if your tracker does not
3983 need that ability::
3985     if newvalues['type'].startswith('image/'):
3986         raise Reject, 'not allowed'
3989 Stop "nosy" messages going to people on vacation
3990 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3992 When users go on vacation and set up vacation email bouncing, you'll
3993 start to see a lot of messages come back through Roundup "Fred is on
3994 vacation". Not very useful, and relatively easy to stop.
3996 1. add a "vacation" flag to your users::
3998          user = Class(db, "user",
3999                     username=String(),   password=Password(),
4000                     address=String(),    realname=String(),
4001                     phone=String(),      organisation=String(),
4002                     alternate_addresses=String(),
4003                     roles=String(), queries=Multilink("query"),
4004                     vacation=Boolean())
4006 2. So that users may edit the vacation flags, add something like the
4007    following to your ``user.item`` template::
4009      <tr>
4010       <th>On Vacation</th> 
4011       <td tal:content="structure context/vacation/field">vacation</td> 
4012      </tr> 
4014 3. edit your detector ``nosyreactor.py`` so that the ``nosyreaction()``
4015    consists of::
4017     def nosyreaction(db, cl, nodeid, oldvalues):
4018         users = db.user
4019         messages = db.msg
4020         # send a copy of all new messages to the nosy list
4021         for msgid in determineNewMessages(cl, nodeid, oldvalues):
4022             try:
4023                 # figure the recipient ids
4024                 sendto = []
4025                 seen_message = {}
4026                 recipients = messages.get(msgid, 'recipients')
4027                 for recipid in messages.get(msgid, 'recipients'):
4028                     seen_message[recipid] = 1
4030                 # figure the author's id, and indicate they've received
4031                 # the message
4032                 authid = messages.get(msgid, 'author')
4034                 # possibly send the message to the author, as long as
4035                 # they aren't anonymous
4036                 if (db.config.MESSAGES_TO_AUTHOR == 'yes' and
4037                         users.get(authid, 'username') != 'anonymous'):
4038                     sendto.append(authid)
4039                 seen_message[authid] = 1
4041                 # now figure the nosy people who weren't recipients
4042                 nosy = cl.get(nodeid, 'nosy')
4043                 for nosyid in nosy:
4044                     # Don't send nosy mail to the anonymous user (that
4045                     # user shouldn't appear in the nosy list, but just
4046                     # in case they do...)
4047                     if users.get(nosyid, 'username') == 'anonymous':
4048                         continue
4049                     # make sure they haven't seen the message already
4050                     if not seen_message.has_key(nosyid):
4051                         # send it to them
4052                         sendto.append(nosyid)
4053                         recipients.append(nosyid)
4055                 # generate a change note
4056                 if oldvalues:
4057                     note = cl.generateChangeNote(nodeid, oldvalues)
4058                 else:
4059                     note = cl.generateCreateNote(nodeid)
4061                 # we have new recipients
4062                 if sendto:
4063                     # filter out the people on vacation
4064                     sendto = [i for i in sendto 
4065                               if not users.get(i, 'vacation', 0)]
4067                     # map userids to addresses
4068                     sendto = [users.get(i, 'address') for i in sendto]
4070                     # update the message's recipients list
4071                     messages.set(msgid, recipients=recipients)
4073                     # send the message
4074                     cl.send_message(nodeid, msgid, note, sendto)
4075             except roundupdb.MessageSendError, message:
4076                 raise roundupdb.DetectorError, message
4078    Note that this is the standard nosy reaction code, with the small
4079    addition of::
4081     # filter out the people on vacation
4082     sendto = [i for i in sendto if not users.get(i, 'vacation', 0)]
4084    which filters out the users that have the vacation flag set to true.
4086 Adding in state transition control
4087 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4089 Sometimes tracker admins want to control the states to which users may
4090 move issues. You can do this by following these steps:
4092 1. make "status" a required variable. This is achieved by adding the
4093    following to the top of the form in the ``issue.item.html``
4094    template::
4096      <input type="hidden" name="@required" value="status">
4098    This will force users to select a status.
4100 2. add a Multilink property to the status class::
4102      stat = Class(db, "status", ... , transitions=Multilink('status'),
4103                   ...)
4105    and then edit the statuses already created, either:
4107    a. through the web using the class list -> status class editor, or
4108    b. using the ``roundup-admin`` "set" command.
4110 3. add an auditor module ``checktransition.py`` in your tracker's
4111    ``detectors`` directory, for example::
4113      def checktransition(db, cl, nodeid, newvalues):
4114          ''' Check that the desired transition is valid for the "status"
4115              property.
4116          '''
4117          if not newvalues.has_key('status'):
4118              return
4119          current = cl.get(nodeid, 'status')
4120          new = newvalues['status']
4121          if new == current:
4122              return
4123          ok = db.status.get(current, 'transitions')
4124          if new not in ok:
4125              raise ValueError, 'Status not allowed to move from "%s" to "%s"'%(
4126                  db.status.get(current, 'name'), db.status.get(new, 'name'))
4128      def init(db):
4129          db.issue.audit('set', checktransition)
4131 4. in the ``issue.item.html`` template, change the status editing bit
4132    from::
4134     <th>Status</th>
4135     <td tal:content="structure context/status/menu">status</td>
4137    to::
4139     <th>Status</th>
4140     <td>
4141      <select tal:condition="context/id" name="status">
4142       <tal:block tal:define="ok context/status/transitions"
4143                  tal:repeat="state db/status/list">
4144        <option tal:condition="python:state.id in ok"
4145                tal:attributes="
4146                     value state/id;
4147                     selected python:state.id == context.status.id"
4148                tal:content="state/name"></option>
4149       </tal:block>
4150      </select>
4151      <tal:block tal:condition="not:context/id"
4152                 tal:replace="structure context/status/menu" />
4153     </td>
4155    which displays only the allowed status to transition to.
4158 Blocking issues that depend on other issues
4159 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4161 We needed the ability to mark certain issues as "blockers" - that is,
4162 they can't be resolved until another issue (the blocker) they rely on is
4163 resolved. To achieve this:
4165 1. Create a new property on the ``issue`` class:
4166    ``blockers=Multilink("issue")``. To do this, edit the definition of
4167    this class in your tracker's ``schema.py`` file. Change this::
4169     issue = IssueClass(db, "issue", 
4170                     assignedto=Link("user"), keyword=Multilink("keyword"),
4171                     priority=Link("priority"), status=Link("status"))
4173    to this, adding the blockers entry::
4175     issue = IssueClass(db, "issue", 
4176                     blockers=Multilink("issue"),
4177                     assignedto=Link("user"), keyword=Multilink("keyword"),
4178                     priority=Link("priority"), status=Link("status"))
4180 2. Add the new ``blockers`` property to the ``issue.item.html`` edit
4181    page, using something like::
4183     <th>Waiting On</th>
4184     <td>
4185      <span tal:replace="structure python:context.blockers.field(showid=1,
4186                                   size=20)" />
4187      <span tal:replace="structure python:db.issue.classhelp('id,title',
4188                                   property='blockers')" />
4189      <span tal:condition="context/blockers"
4190            tal:repeat="blk context/blockers">
4191       <br>View: <a tal:attributes="href string:issue${blk/id}"
4192                    tal:content="blk/id"></a>
4193      </span>
4194     </td>
4196    You'll need to fiddle with your item page layout to find an
4197    appropriate place to put it - I'll leave that fun part up to you.
4198    Just make sure it appears in the first table, possibly somewhere near
4199    the "superseders" field.
4201 3. Create a new detector module (see below) which enforces the rules:
4203    - issues may not be resolved if they have blockers
4204    - when a blocker is resolved, it's removed from issues it blocks
4206    The contents of the detector should be something like this::
4209     def blockresolution(db, cl, nodeid, newvalues):
4210         ''' If the issue has blockers, don't allow it to be resolved.
4211         '''
4212         if nodeid is None:
4213             blockers = []
4214         else:
4215             blockers = cl.get(nodeid, 'blockers')
4216         blockers = newvalues.get('blockers', blockers)
4218         # don't do anything if there's no blockers or the status hasn't
4219         # changed
4220         if not blockers or not newvalues.has_key('status'):
4221             return
4223         # get the resolved state ID
4224         resolved_id = db.status.lookup('resolved')
4226         # format the info
4227         u = db.config.TRACKER_WEB
4228         s = ', '.join(['<a href="%sissue%s">%s</a>'%(
4229                         u,id,id) for id in blockers])
4230         if len(blockers) == 1:
4231             s = 'issue %s is'%s
4232         else:
4233             s = 'issues %s are'%s
4235         # ok, see if we're trying to resolve
4236         if newvalues['status'] == resolved_id:
4237             raise ValueError, "This issue can't be resolved until %s resolved."%s
4240     def resolveblockers(db, cl, nodeid, oldvalues):
4241         ''' When we resolve an issue that's a blocker, remove it from the
4242             blockers list of the issue(s) it blocks.
4243         '''
4244         newstatus = cl.get(nodeid,'status')
4246         # no change?
4247         if oldvalues.get('status', None) == newstatus:
4248             return
4250         resolved_id = db.status.lookup('resolved')
4252         # interesting?
4253         if newstatus != resolved_id:
4254             return
4256         # yes - find all the blocked issues, if any, and remove me from
4257         # their blockers list
4258         issues = cl.find(blockers=nodeid)
4259         for issueid in issues:
4260             blockers = cl.get(issueid, 'blockers')
4261             if nodeid in blockers:
4262                 blockers.remove(nodeid)
4263                 cl.set(issueid, blockers=blockers)
4265     def init(db):
4266         # might, in an obscure situation, happen in a create
4267         db.issue.audit('create', blockresolution)
4268         db.issue.audit('set', blockresolution)
4270         # can only happen on a set
4271         db.issue.react('set', resolveblockers)
4273    Put the above code in a file called "blockers.py" in your tracker's
4274    "detectors" directory.
4276 4. Finally, and this is an optional step, modify the tracker web page
4277    URLs so they filter out issues with any blockers. You do this by
4278    adding an additional filter on "blockers" for the value "-1". For
4279    example, the existing "Show All" link in the "page" template (in the
4280    tracker's "html" directory) looks like this::
4282     <a href="#"
4283        tal:attributes="href python:request.indexargs_url('issue', {
4284       '@sort': '-activity',
4285       '@group': 'priority',
4286       '@filter': 'status',
4287       '@columns': columns_showall,
4288       '@search_text': '',
4289       'status': status_notresolved,
4290       '@dispname': i18n.gettext('Show All'),
4291      })"
4292        i18n:translate="">Show All</a><br>
4294    modify it to add the "blockers" info to the URL (note, both the
4295    "@filter" *and* "blockers" values must be specified)::
4297     <a href="#"
4298        tal:attributes="href python:request.indexargs_url('issue', {
4299       '@sort': '-activity',
4300       '@group': 'priority',
4301       '@filter': 'status,blockers',
4302       '@columns': columns_showall,
4303       '@search_text': '',
4304       'status': status_notresolved,
4305       'blockers': '-1',
4306       '@dispname': i18n.gettext('Show All'),
4307      })"
4308        i18n:translate="">Show All</a><br>
4310    The above examples are line-wrapped on the trailing & and should
4311    be unwrapped.
4313 That's it. You should now be able to set blockers on your issues. Note
4314 that if you want to know whether an issue has any other issues dependent
4315 on it (i.e. it's in their blockers list) you can look at the journal
4316 history at the bottom of the issue page - look for a "link" event to
4317 another issue's "blockers" property.
4319 Add users to the nosy list based on the keyword
4320 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4322 Let's say we need the ability to automatically add users to the nosy
4323 list based
4324 on the occurance of a keyword. Every user should be allowed to edit their
4325 own list of keywords for which they want to be added to the nosy list.
4327 Below, we'll show that this change can be done with minimal
4328 understanding of the Roundup system, using only copy and paste.
4330 This requires three changes to the tracker: a change in the database to
4331 allow per-user recording of the lists of keywords for which he wants to
4332 be put on the nosy list, a change in the user view allowing them to edit
4333 this list of keywords, and addition of an auditor which updates the nosy
4334 list when a keyword is set.
4336 Adding the nosy keyword list
4337 ::::::::::::::::::::::::::::
4339 The change to make in the database, is that for any user there should be a list
4340 of keywords for which he wants to be put on the nosy list. Adding a
4341 ``Multilink`` of ``keyword`` seems to fullfill this. As such, all that has to
4342 be done is to add a new field to the definition of ``user`` within the file
4343 ``schema.py``.  We will call this new field ``nosy_keywords``, and the updated
4344 definition of user will be::
4346     user = Class(db, "user", 
4347                     username=String(),   password=Password(),
4348                     address=String(),    realname=String(), 
4349                     phone=String(),      organisation=String(),
4350                     alternate_addresses=String(),
4351                     queries=Multilink('query'), roles=String(),
4352                     timezone=String(),
4353                     nosy_keywords=Multilink('keyword'))
4354  
4355 Changing the user view to allow changing the nosy keyword list
4356 ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
4358 We want any user to be able to change the list of keywords for which
4359 he will by default be added to the nosy list. We choose to add this
4360 to the user view, as is generated by the file ``html/user.item.html``.
4361 We can easily 
4362 see that the keyword field in the issue view has very similar editing
4363 requirements as our nosy keywords, both being lists of keywords. As
4364 such, we look for Keywords in ``issue.item.html``, and extract the
4365 associated parts from there. We add this to ``user.item.html`` at the 
4366 bottom of the list of viewed items (i.e. just below the 'Alternate
4367 E-mail addresses' in the classic template)::
4369  <tr>
4370   <th>Nosy Keywords</th>
4371   <td>
4372   <span tal:replace="structure context/nosy_keywords/field" />
4373   <span tal:replace="structure python:db.keyword.classhelp(property='nosy_keywords')" />
4374   </td>
4375  </tr>
4376   
4378 Addition of an auditor to update the nosy list
4379 ::::::::::::::::::::::::::::::::::::::::::::::
4381 The more difficult part is the logic to add
4382 the users to the nosy list when required. 
4383 We choose to perform this action whenever the keywords on an
4384 item are set (this includes the creation of items).
4385 Here we choose to start out with a copy of the 
4386 ``detectors/nosyreaction.py`` detector, which we copy to the file
4387 ``detectors/nosy_keyword_reaction.py``. 
4388 This looks like a good start as it also adds users
4389 to the nosy list. A look through the code reveals that the
4390 ``nosyreaction`` function actually sends the e-mail. 
4391 We don't need this. Therefore, we can change the ``init`` function to::
4393     def init(db):
4394         db.issue.audit('create', update_kw_nosy)
4395         db.issue.audit('set', update_kw_nosy)
4397 After that, we rename the ``updatenosy`` function to ``update_kw_nosy``.
4398 The first two blocks of code in that function relate to setting
4399 ``current`` to a combination of the old and new nosy lists. This
4400 functionality is left in the new auditor. The following block of
4401 code, which handled adding the assignedto user(s) to the nosy list in
4402 ``updatenosy``, should be replaced by a block of code to add the
4403 interested users to the nosy list. We choose here to loop over all
4404 new keywords, than looping over all users,
4405 and assign the user to the nosy list when the keyword occurs in the user's
4406 ``nosy_keywords``. The next part in ``updatenosy`` -- adding the author
4407 and/or recipients of a message to the nosy list -- is obviously not
4408 relevant here and is thus deleted from the new auditor. The last
4409 part, copying the new nosy list to ``newvalues``, can stay as is.
4410 This results in the following function::
4412     def update_kw_nosy(db, cl, nodeid, newvalues):
4413         '''Update the nosy list for changes to the keywords
4414         '''
4415         # nodeid will be None if this is a new node
4416         current = {}
4417         if nodeid is None:
4418             ok = ('new', 'yes')
4419         else:
4420             ok = ('yes',)
4421             # old node, get the current values from the node if they haven't
4422             # changed
4423             if not newvalues.has_key('nosy'):
4424                 nosy = cl.get(nodeid, 'nosy')
4425                 for value in nosy:
4426                     if not current.has_key(value):
4427                         current[value] = 1
4429         # if the nosy list changed in this transaction, init from the new value
4430         if newvalues.has_key('nosy'):
4431             nosy = newvalues.get('nosy', [])
4432             for value in nosy:
4433                 if not db.hasnode('user', value):
4434                     continue
4435                 if not current.has_key(value):
4436                     current[value] = 1
4438         # add users with keyword in nosy_keywords to the nosy list
4439         if newvalues.has_key('keyword') and newvalues['keyword'] is not None:
4440             keyword_ids = newvalues['keyword']
4441             for keyword in keyword_ids:
4442                 # loop over all users,
4443                 # and assign user to nosy when keyword in nosy_keywords
4444                 for user_id in db.user.list():
4445                     nosy_kw = db.user.get(user_id, "nosy_keywords")
4446                     found = 0
4447                     for kw in nosy_kw:
4448                         if kw == keyword:
4449                             found = 1
4450                     if found:
4451                         current[user_id] = 1
4453         # that's it, save off the new nosy list
4454         newvalues['nosy'] = current.keys()
4456 These two function are the only ones needed in the file.
4458 TODO: update this example to use the ``find()`` Class method.
4460 Caveats
4461 :::::::
4463 A few problems with the design here can be noted:
4465 Multiple additions
4466     When a user, after automatic selection, is manually removed
4467     from the nosy list, he is added to the nosy list again when the
4468     keyword list of the issue is updated. A better design might be
4469     to only check which keywords are new compared to the old list
4470     of keywords, and only add users when they have indicated
4471     interest on a new keyword.
4473     The code could also be changed to only trigger on the ``create()``
4474     event, rather than also on the ``set()`` event, thus only setting
4475     the nosy list when the issue is created.
4477 Scalability
4478     In the auditor, there is a loop over all users. For a site with
4479     only few users this will pose no serious problem; however, with
4480     many users this will be a serious performance bottleneck.
4481     A way out would be to link from the keywords to the users who
4482     selected these keywords as nosy keywords. This will eliminate the
4483     loop over all users.
4485 Changes to Security and Permissions
4486 -----------------------------------
4488 Restricting the list of users that are assignable to a task
4489 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4491 1. In your tracker's ``schema.py``, create a new Role, say "Developer"::
4493      db.security.addRole(name='Developer', description='A developer')
4495 2. Just after that, create a new Permission, say "Fixer", specific to
4496    "issue"::
4498      p = db.security.addPermission(name='Fixer', klass='issue',
4499          description='User is allowed to be assigned to fix issues')
4501 3. Then assign the new Permission to your "Developer" Role::
4503      db.security.addPermissionToRole('Developer', p)
4505 4. In the issue item edit page (``html/issue.item.html`` in your tracker
4506    directory), use the new Permission in restricting the "assignedto"
4507    list::
4509     <select name="assignedto">
4510      <option value="-1">- no selection -</option>
4511      <tal:block tal:repeat="user db/user/list">
4512      <option tal:condition="python:user.hasPermission(
4513                                 'Fixer', context._classname)"
4514              tal:attributes="
4515                 value user/id;
4516                 selected python:user.id == context.assignedto"
4517              tal:content="user/realname"></option>
4518      </tal:block>
4519     </select>
4521 For extra security, you may wish to setup an auditor to enforce the
4522 Permission requirement (install this as ``assignedtoFixer.py`` in your
4523 tracker ``detectors`` directory)::
4525   def assignedtoMustBeFixer(db, cl, nodeid, newvalues):
4526       ''' Ensure the assignedto value in newvalues is used with the
4527           Fixer Permission
4528       '''
4529       if not newvalues.has_key('assignedto'):
4530           # don't care
4531           return
4532   
4533       # get the userid
4534       userid = newvalues['assignedto']
4535       if not db.security.hasPermission('Fixer', userid, cl.classname):
4536           raise ValueError, 'You do not have permission to edit %s'%cl.classname
4538   def init(db):
4539       db.issue.audit('set', assignedtoMustBeFixer)
4540       db.issue.audit('create', assignedtoMustBeFixer)
4542 So now, if an edit action attempts to set "assignedto" to a user that
4543 doesn't have the "Fixer" Permission, the error will be raised.
4546 Users may only edit their issues
4547 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4549 In this case, users registering themselves are granted Provisional
4550 access, meaning they
4551 have access to edit the issues they submit, but not others. We create a new
4552 Role called "Provisional User" which is granted to newly-registered users,
4553 and has limited access. One of the Permissions they have is the new "Edit
4554 Own" on issues (regular users have "Edit".)
4556 First up, we create the new Role and Permission structure in
4557 ``schema.py``::
4559     #
4560     # New users not approved by the admin
4561     #
4562     db.security.addRole(name='Provisional User',
4563         description='New user registered via web or email')
4565     # These users need to be able to view and create issues but only edit
4566     # and view their own
4567     db.security.addPermissionToRole('Provisional User', 'Create', 'issue')
4568     def own_issue(db, userid, itemid):
4569         '''Determine whether the userid matches the creator of the issue.'''
4570         return userid == db.issue.get(itemid, 'creator')
4571     p = db.security.addPermission(name='Edit', klass='issue',
4572         check=own_issue, description='Can only edit own issues')
4573     db.security.addPermissionToRole('Provisional User', p)
4574     p = db.security.addPermission(name='View', klass='issue',
4575         check=own_issue, description='Can only view own issues')
4576     db.security.addPermissionToRole('Provisional User', p)
4578     # Assign the Permissions for issue-related classes
4579     for cl in 'file', 'msg', 'query', 'keyword':
4580         db.security.addPermissionToRole('Provisional User', 'View', cl)
4581         db.security.addPermissionToRole('Provisional User', 'Edit', cl)
4582         db.security.addPermissionToRole('Provisional User', 'Create', cl)
4583     for cl in 'priority', 'status':
4584         db.security.addPermissionToRole('Provisional User', 'View', cl)
4586     # and give the new users access to the web and email interface
4587     db.security.addPermissionToRole('Provisional User', 'Web Access')
4588     db.security.addPermissionToRole('Provisional User', 'Email Access')
4590     # make sure they can view & edit their own user record
4591     def own_record(db, userid, itemid):
4592         '''Determine whether the userid matches the item being accessed.'''
4593         return userid == itemid
4594     p = db.security.addPermission(name='View', klass='user', check=own_record,
4595         description="User is allowed to view their own user details")
4596     db.security.addPermissionToRole('Provisional User', p)
4597     p = db.security.addPermission(name='Edit', klass='user', check=own_record,
4598         description="User is allowed to edit their own user details")
4599     db.security.addPermissionToRole('Provisional User', p)
4601 Then, in ``config.ini``, we change the Role assigned to newly-registered
4602 users, replacing the existing ``'User'`` values::
4604     [main]
4605     ...
4606     new_web_user_roles = 'Provisional User'
4607     new_email_user_roles = 'Provisional User'
4610 All users may only view and edit issues, files and messages they create
4611 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4613 Replace the standard "classic" tracker View and Edit Permission assignments
4614 for the "issue", "file" and "msg" classes with the following::
4616     def checker(klass):
4617         def check(db, userid, itemid, klass=klass):
4618             return db.getclass(klass).get(itemid, 'creator') == userid
4619         return check
4620     for cl in 'issue', 'file', 'msg':
4621         p = db.security.addPermission(name='View', klass=cl,
4622             check=checker(cl))
4623         db.security.addPermissionToRole('User', p)
4624         p = db.security.addPermission(name='Edit', klass=cl,
4625             check=checker(cl))
4626         db.security.addPermissionToRole('User', p)
4627         db.security.addPermissionToRole('User', 'Create', cl)
4630 Moderating user registration
4631 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4633 You could set up new-user moderation in a public tracker by:
4635 1. creating a new highly-restricted user role "Pending",
4636 2. set the config new_web_user_roles and/or new_email_user_roles to that
4637    role,
4638 3. have an auditor that emails you when new users are created with that
4639    role using roundup.mailer
4640 4. edit the role to "User" for valid users.
4642 Some simple javascript might help in the last step. If you have high volume
4643 you could search for all currently-Pending users and do a bulk edit of all
4644 their roles at once (again probably with some simple javascript help).
4647 Changes to the Web User Interface
4648 ---------------------------------
4650 Adding action links to the index page
4651 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4653 Add a column to the ``item.index.html`` template.
4655 Resolving the issue::
4657   <a tal:attributes="href
4658      string:issue${i/id}?:status=resolved&:action=edit">resolve</a>
4660 "Take" the issue::
4662   <a tal:attributes="href
4663      string:issue${i/id}?:assignedto=${request/user/id}&:action=edit">take</a>
4665 ... and so on.
4667 Colouring the rows in the issue index according to priority
4668 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4670 A simple ``tal:attributes`` statement will do the bulk of the work here. In
4671 the ``issue.index.html`` template, add this to the ``<tr>`` that
4672 displays the rows of data::
4674    <tr tal:attributes="class string:priority-${i/priority/plain}">
4676 and then in your stylesheet (``style.css``) specify the colouring for the
4677 different priorities, as follows::
4679    tr.priority-critical td {
4680        background-color: red;
4681    }
4683    tr.priority-urgent td {
4684        background-color: orange;
4685    }
4687 and so on, with far less offensive colours :)
4689 Editing multiple items in an index view
4690 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4692 To edit the status of all items in the item index view, edit the
4693 ``issue.item.html``:
4695 1. add a form around the listing table (separate from the existing
4696    index-page form), so at the top it reads::
4698     <form method="POST" tal:attributes="action request/classname">
4699      <table class="list">
4701    and at the bottom of that table::
4703      </table>
4704     </form
4706    making sure you match the ``</table>`` from the list table, not the
4707    navigation table or the subsequent form table.
4709 2. in the display for the issue property, change::
4711     <td tal:condition="request/show/status"
4712         tal:content="python:i.status.plain() or default">&nbsp;</td>
4714    to::
4716     <td tal:condition="request/show/status"
4717         tal:content="structure i/status/field">&nbsp;</td>
4719    this will result in an edit field for the status property.
4721 3. after the ``tal:block`` which lists the index items (marked by
4722    ``tal:repeat="i batch"``) add a new table row::
4724     <tr>
4725      <td tal:attributes="colspan python:len(request.columns)">
4726       <input type="submit" value=" Save Changes ">
4727       <input type="hidden" name="@action" value="edit">
4728       <tal:block replace="structure request/indexargs_form" />
4729      </td>
4730     </tr>
4732    which gives us a submit button, indicates that we are performing an edit
4733    on any changed statuses. The final ``tal:block`` will make sure that the
4734    current index view parameters (filtering, columns, etc) will be used in 
4735    rendering the next page (the results of the editing).
4738 Displaying only message summaries in the issue display
4739 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4741 Alter the ``issue.item`` template section for messages to::
4743  <table class="messages" tal:condition="context/messages">
4744   <tr><th colspan="5" class="header">Messages</th></tr>
4745   <tr tal:repeat="msg context/messages">
4746    <td><a tal:attributes="href string:msg${msg/id}"
4747           tal:content="string:msg${msg/id}"></a></td>
4748    <td tal:content="msg/author">author</td>
4749    <td class="date" tal:content="msg/date/pretty">date</td>
4750    <td tal:content="msg/summary">summary</td>
4751    <td>
4752     <a tal:attributes="href string:?@remove@messages=${msg/id}&@action=edit">
4753     remove</a>
4754    </td>
4755   </tr>
4756  </table>
4759 Enabling display of either message summaries or the entire messages
4760 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4762 This is pretty simple - all we need to do is copy the code from the
4763 example `displaying only message summaries in the issue display`_ into
4764 our template alongside the summary display, and then introduce a switch
4765 that shows either the one or the other. We'll use a new form variable,
4766 ``@whole_messages`` to achieve this::
4768  <table class="messages" tal:condition="context/messages">
4769   <tal:block tal:condition="not:request/form/@whole_messages/value | python:0">
4770    <tr><th colspan="3" class="header">Messages</th>
4771        <th colspan="2" class="header">
4772          <a href="?@whole_messages=yes">show entire messages</a>
4773        </th>
4774    </tr>
4775    <tr tal:repeat="msg context/messages">
4776     <td><a tal:attributes="href string:msg${msg/id}"
4777            tal:content="string:msg${msg/id}"></a></td>
4778     <td tal:content="msg/author">author</td>
4779     <td class="date" tal:content="msg/date/pretty">date</td>
4780     <td tal:content="msg/summary">summary</td>
4781     <td>
4782      <a tal:attributes="href string:?@remove@messages=${msg/id}&@action=edit">remove</a>
4783     </td>
4784    </tr>
4785   </tal:block>
4787   <tal:block tal:condition="request/form/@whole_messages/value | python:0">
4788    <tr><th colspan="2" class="header">Messages</th>
4789        <th class="header">
4790          <a href="?@whole_messages=">show only summaries</a>
4791        </th>
4792    </tr>
4793    <tal:block tal:repeat="msg context/messages">
4794     <tr>
4795      <th tal:content="msg/author">author</th>
4796      <th class="date" tal:content="msg/date/pretty">date</th>
4797      <th style="text-align: right">
4798       (<a tal:attributes="href string:?@remove@messages=${msg/id}&@action=edit">remove</a>)
4799      </th>
4800     </tr>
4801     <tr><td colspan="3" tal:content="msg/content"></td></tr>
4802    </tal:block>
4803   </tal:block>
4804  </table>
4807 Setting up a "wizard" (or "druid") for controlled adding of issues
4808 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4810 1. Set up the page templates you wish to use for data input. My wizard
4811    is going to be a two-step process: first figuring out what category
4812    of issue the user is submitting, and then getting details specific to
4813    that category. The first page includes a table of help, explaining
4814    what the category names mean, and then the core of the form::
4816     <form method="POST" onSubmit="return submit_once()"
4817           enctype="multipart/form-data">
4818       <input type="hidden" name="@template" value="add_page1">
4819       <input type="hidden" name="@action" value="page1_submit">
4821       <strong>Category:</strong>
4822       <tal:block tal:replace="structure context/category/menu" />
4823       <input type="submit" value="Continue">
4824     </form>
4826    The next page has the usual issue entry information, with the
4827    addition of the following form fragments::
4829     <form method="POST" onSubmit="return submit_once()"
4830           enctype="multipart/form-data"
4831           tal:condition="context/is_edit_ok"
4832           tal:define="cat request/form/category/value">
4834       <input type="hidden" name="@template" value="add_page2">
4835       <input type="hidden" name="@required" value="title">
4836       <input type="hidden" name="category" tal:attributes="value cat">
4837        .
4838        .
4839        .
4840     </form>
4842    Note that later in the form, I use the value of "cat" to decide which
4843    form elements should be displayed. For example::
4845     <tal:block tal:condition="python:cat in '6 10 13 14 15 16 17'.split()">
4846      <tr>
4847       <th>Operating System</th>
4848       <td tal:content="structure context/os/field"></td>
4849      </tr>
4850      <tr>
4851       <th>Web Browser</th>
4852       <td tal:content="structure context/browser/field"></td>
4853      </tr>
4854     </tal:block>
4856    ... the above section will only be displayed if the category is one
4857    of 6, 10, 13, 14, 15, 16 or 17.
4859 3. Determine what actions need to be taken between the pages - these are
4860    usually to validate user choices and determine what page is next. Now encode
4861    those actions in a new ``Action`` class (see `defining new web actions`_)::
4863     from roundup.cgi.actions import Action
4865     class Page1SubmitAction(Action):
4866         def handle(self):
4867             ''' Verify that the user has selected a category, and then move
4868                 on to page 2.
4869             '''
4870             category = self.form['category'].value
4871             if category == '-1':
4872                 self.client.error_message.append('You must select a category of report')
4873                 return
4874             # everything's ok, move on to the next page
4875             self.client.template = 'add_page2'
4877     def init(instance):
4878         instance.registerAction('page1_submit', Page1SubmitAction)
4880 4. Use the usual "new" action as the ``@action`` on the final page, and
4881    you're done (the standard context/submit method can do this for you).
4884 Debugging Trackers
4885 ==================
4887 There are three switches in tracker configs that turn on debugging in
4888 Roundup:
4890 1. web :: debug
4891 2. mail :: debug
4892 3. logging :: level
4894 See the config.ini file or the `tracker configuration`_ section above for
4895 more information.
4897 Additionally, the ``roundup-server.py`` script has its own debugging mode
4898 in which it reloads edited templates immediately when they are changed,
4899 rather than requiring a web server restart.
4902 .. _`design documentation`: design.html
4903 .. _`developer's guide`: developers.html