Code

5273e80fe048fdb173b5e9c2409ac4fb4297e7a4
[roundup.git] / doc / customizing.txt
1 ===================
2 Customising Roundup
3 ===================
5 :Version: $Revision: 1.223 $
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  http_auth -- ``yes``
185   Whether to use HTTP Basic Authentication, if present.
186   Roundup will use either the REMOTE_USER or HTTP_AUTHORIZATION
187   variables supplied by your web server (in that order).
188   Set this option to 'no' if you do not wish to use HTTP Basic
189   Authentication in your web interface.
191  use_browser_language -- ``yes``
192   Whether to use HTTP Accept-Language, if present.
193   Browsers send a language-region preference list.
194   It's usually set in the client's browser or in their
195   Operating System.
196   Set this option to 'no' if you want to ignore it.
198  debug -- ``no``
199   Setting this option makes Roundup display error tracebacks
200   in the user's browser rather than emailing them to the
201   tracker admin."),
203 Section **rdbms**
204  Settings in this section are used by Postgresql and MySQL backends only
206  name -- ``roundup``
207   Name of the database to use.
209  host -- ``localhost``
210   Database server host.
212  port -- default *blank*
213   TCP port number of the database server. Postgresql usually resides on
214   port 5432 (if any), for MySQL default port number is 3306. Leave this
215   option empty to use backend default.
217  user -- ``roundup``
218   Database user name that Roundup should use.
220  password -- ``roundup``
221   Database user password.
223  read_default_file -- ``~/.my.cnf``
224   Name of the MySQL defaults file. Only used in MySQL connections.
226  read_default_group -- ``roundup``
227   Name of the group to use in the MySQL defaults file. Only used in
228   MySQL connections.
230 Section **logging**
231  config -- default *blank*
232   Path to configuration file for standard Python logging module. If this
233   option is set, logging configuration is loaded from specified file;
234   options 'filename' and 'level' in this section are ignored. The path may
235   be either absolute or relative to the directory containig this config file.
237  filename -- default *blank*
238   Log file name for minimal logging facility built into Roundup.  If no file
239   name specified, log messages are written on stderr. If above 'config'
240   option is set, this option has no effect. The path may be either absolute
241   or relative to the directory containig this config file.
243  level -- ``ERROR``
244   Minimal severity level of messages written to log file. If above 'config'
245   option is set, this option has no effect.
246   Allowed values: ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR``
248 Section **mail**
249  Outgoing email options. Used for nosy messages, password reset and
250  registration approval requests.
252  domain -- ``localhost``
253   Domain name used for email addresses.
255  host -- default *blank*
256   SMTP mail host that roundup will use to send mail
258  username -- default *blank*
259   SMTP login name. Set this if your mail host requires authenticated access.
260   If username is not empty, password (below) MUST be set!
262  password -- default *blank*
263   SMTP login password.
264   Set this if your mail host requires authenticated access.
266  port -- default *25*
267   SMTP port on mail host.
268   Set this if your mail host runs on a different port.
270  local_hostname -- default *blank*
271   The fully qualified domain name (FQDN) to use during SMTP sessions. If left
272   blank, the underlying SMTP library will attempt to detect your FQDN. If your
273   mail host requires something specific, specify the FQDN to use.
275  tls -- ``no``
276   If your SMTP mail host provides or requires TLS (Transport Layer Security)
277   then you may set this option to 'yes'.
278   Allowed values: ``yes``, ``no``
280  tls_keyfile -- default *blank*
281   If TLS is used, you may set this option to the name of a PEM formatted
282   file that contains your private key. The path may be either absolute or
283   relative to the directory containig this config file.
285  tls_certfile -- default *blank*
286   If TLS is used, you may set this option to the name of a PEM formatted
287   certificate chain file. The path may be either absolute or relative
288   to the directory containig this config file.
290  charset -- utf-8
291   Character set to encode email headers with. We use utf-8 by default, as
292   it's the most flexible. Some mail readers (eg. Eudora) can't cope with
293   that, so you might need to specify a more limited character set
294   (eg. iso-8859-1).
296  debug -- default *blank*
297   Setting this option makes Roundup to write all outgoing email messages
298   to this file *instead* of sending them. This option has the same effect
299   as environment variable SENDMAILDEBUG. Environment variable takes
300   precedence. The path may be either absolute or relative to the directory
301   containig this config file.
303  add_authorinfo -- ``yes``
304   Add a line with author information at top of all messages send by
305   roundup.
307  add_authoremail -- ``yes``
308   Add the mail address of the author to the author information at the
309   top of all messages.  If this is false but add_authorinfo is true,
310   only the name of the actor is added which protects the mail address
311   of the actor from being exposed at mail archives, etc.
313 Section **mailgw**
314  Roundup Mail Gateway options
316  keep_quoted_text -- ``yes``
317   Keep email citations when accepting messages. Setting this to ``no`` strips
318   out "quoted" text from the message. Signatures are also stripped.
319   Allowed values: ``yes``, ``no``
321  leave_body_unchanged -- ``no``
322   Preserve the email body as is - that is, keep the citations *and*
323   signatures.
324   Allowed values: ``yes``, ``no``
326  default_class -- ``issue``
327   Default class to use in the mailgw if one isn't supplied in email subjects.
328   To disable, leave the value blank.
330  language -- default *blank*
331   Default locale name for the tracker mail gateway.  If this option is
332   not set, mail gateway will use the language of the tracker instance.
334  subject_prefix_parsing -- ``strict``
335   Controls the parsing of the [prefix] on subject lines in incoming emails.
336   ``strict`` will return an error to the sender if the [prefix] is not
337   recognised. ``loose`` will attempt to parse the [prefix] but just
338   pass it through as part of the issue title if not recognised. ``none``
339   will always pass any [prefix] through as part of the issue title.
341  subject_suffix_parsing -- ``strict``
342   Controls the parsing of the [suffix] on subject lines in incoming emails.
343   ``strict`` will return an error to the sender if the [suffix] is not
344   recognised. ``loose`` will attempt to parse the [suffix] but just
345   pass it through as part of the issue title if not recognised. ``none``
346   will always pass any [suffix] through as part of the issue title.
348  subject_suffix_delimiters -- ``[]``
349   Defines the brackets used for delimiting the commands suffix in a subject
350   line.
352  subject_content_match -- ``always``
353   Controls matching of the incoming email subject line against issue titles
354   in the case where there is no designator [prefix]. ``never`` turns off
355   matching. ``creation + interval`` or ``activity + interval`` will match
356   an issue for the interval after the issue's creation or last activity.
357   The interval is a standard Roundup interval.
359  refwd_re -- ``(\s*\W?\s*(fw|fwd|re|aw|sv|ang)\W)+``
360   Regular expression matching a single reply or forward prefix
361   prepended by the mailer. This is explicitly stripped from the
362   subject during parsing.  Value is Python Regular Expression
363   (UTF8-encoded).
365  origmsg_re -- `` ^[>|\s]*-----\s?Original Message\s?-----$``
366   Regular expression matching start of an original message if quoted
367   the in body.  Value is Python Regular Expression (UTF8-encoded).
369  sign_re -- ``^[>|\s]*-- ?$``
370   Regular expression matching the start of a signature in the message
371   body.  Value is Python Regular Expression (UTF8-encoded).
373  eol_re -- ``[\r\n]+``
374   Regular expression matching end of line.  Value is Python Regular
375   Expression (UTF8-encoded).
377  blankline_re -- ``[\r\n]+\s*[\r\n]+``
378   Regular expression matching a blank line.  Value is Python Regular
379   Expression (UTF8-encoded).
381 Section **pgp**
382  OpenPGP mail processing options
384  enable -- ``no``
385   Enable PGP processing. Requires pyme.
387  roles -- default *blank*
388   If specified, a comma-separated list of roles to perform PGP
389   processing on. If not specified, it happens for all users.
391  homedir -- default *blank*
392   Location of PGP directory. Defaults to $HOME/.gnupg if not
393   specified.
395 Section **nosy**
396  Nosy messages sending
398  messages_to_author -- ``no``
399   Send nosy messages to the author of the message.
400   Allowed values: ``yes``, ``no``, ``new``
402  signature_position -- ``bottom``
403   Where to place the email signature.
404   Allowed values: ``top``, ``bottom``, ``none``
406  add_author -- ``new``
407   Does the author of a message get placed on the nosy list automatically?
408   If ``new`` is used, then the author will only be added when a message
409   creates a new issue. If ``yes``, then the author will be added on
410   followups too. If ``no``, they're never added to the nosy.
411   Allowed values: ``yes``, ``no``, ``new``
412   
413  add_recipients -- ``new``
414   Do the recipients (``To:``, ``Cc:``) of a message get placed on the nosy
415   list?  If ``new`` is used, then the recipients will only be added when a
416   message creates a new issue. If ``yes``, then the recipients will be added
417   on followups too. If ``no``, they're never added to the nosy.
418   Allowed values: ``yes``, ``no``, ``new``
420  email_sending -- ``single``
421   Controls the email sending from the nosy reactor. If ``multiple`` then
422   a separate email is sent to each recipient. If ``single`` then a single
423   email is sent with each recipient as a CC address.
425  max_attachment_size -- ``2147483647``
426   Attachments larger than the given number of bytes won't be attached
427   to nosy mails. They will be replaced by a link to the tracker's
428   download page for the file.
431 You may generate a new default config file using the ``roundup-admin
432 genconfig`` command.
434 Configuration variables may be referred to in lower or upper case. In code,
435 variables not in the "main" section are referred to using their section and
436 name, so "domain" in the section "mail" becomes MAIL_DOMAIN. The
437 configuration variables available are:
439 Extending the configuration file
440 --------------------------------
442 You can't add new variables to the config.ini file in the tracker home but
443 you can add two new config.ini files:
445 - a config.ini in the ``extensions`` directory will be loaded and attached
446   to the config variable as "ext".
447 - a config.ini in the ``detectors`` directory will be loaded and attached
448   to the config variable as "detectors".
450 For example, the following in ``detectors/config.ini``::
452     [main]
453     qa_recipients = email@example.com
455 is accessible as::
457     db.config.detectors['QA_RECIPIENTS']
459 Note that the name grouping applied to the main configuration file is
460 applied to the extension config files, so if you instead have::
462     [qa]
463     recipients = email@example.com
465 then the above ``db.config.detectors['QA_RECIPIENTS']`` will still work.
468 Tracker Schema
469 ==============
471 .. note::
472    if you modify the schema, you'll most likely need to edit the
473    `web interface`_ HTML template files and `detectors`_ to reflect
474    your changes.
476 A tracker schema defines what data is stored in the tracker's database.
477 Schemas are defined using Python code in the ``schema.py`` module of your
478 tracker.
480 The ``schema.py`` module
481 ------------------------
483 The ``schema.py`` module contains two functions:
485 **open**
486   This function defines what your tracker looks like on the inside, the
487   **schema** of the tracker. It defines the **Classes** and **properties**
488   on each class. It also defines the **security** for those Classes. The
489   next few sections describe how schemas work and what you can do with
490   them.
491 **init**
492   This function is responsible for setting up the initial state of your
493   tracker. It's called exactly once - but the ``roundup-admin initialise``
494   command.  See the start of the section on `database content`_ for more
495   info about how this works.
498 The "classic" schema
499 --------------------
501 The "classic" schema looks like this (see section `setkey(property)`_
502 below for the meaning of ``'setkey'`` -- you may also want to look into
503 the sections `setlabelprop(property)`_ and `setorderprop(property)`_ for
504 specifying (default) labelling and ordering of classes.)::
506     pri = Class(db, "priority", name=String(), order=String())
507     pri.setkey("name")
509     stat = Class(db, "status", name=String(), order=String())
510     stat.setkey("name")
512     keyword = Class(db, "keyword", name=String())
513     keyword.setkey("name")
515     user = Class(db, "user", username=String(), organisation=String(),
516         password=String(), address=String(), realname=String(),
517         phone=String(), alternate_addresses=String(),
518         queries=Multilink('query'), roles=String(), timezone=String())
519     user.setkey("username")
521     msg = FileClass(db, "msg", author=Link("user"), summary=String(),
522         date=Date(), recipients=Multilink("user"),
523         files=Multilink("file"), messageid=String(), inreplyto=String())
525     file = FileClass(db, "file", name=String())
527     issue = IssueClass(db, "issue", keyword=Multilink("keyword"),
528         status=Link("status"), assignedto=Link("user"),
529         priority=Link("priority"))
530     issue.setkey('title')
533 What you can't do to the schema
534 -------------------------------
536 You must never:
538 **Remove the users class**
539   This class is the only *required* class in Roundup.
541 **Remove the "username", "address", "password" or "realname" user properties**
542   Various parts of Roundup require these properties. Don't remove them.
544 **Change the type of a property**
545   Property types must *never* be changed - the database simply doesn't take
546   this kind of action into account. Note that you can't just remove a
547   property and re-add it as a new type either. If you wanted to make the
548   assignedto property a Multilink, you'd need to create a new property
549   assignedto_list and remove the old assignedto property.
552 What you can do to the schema
553 -----------------------------
555 Your schema may be changed at any time before or after the tracker has been
556 initialised (or used). You may:
558 **Add new properties to classes, or add whole new classes**
559   This is painless and easy to do - there are generally no repurcussions
560   from adding new information to a tracker's schema.
562 **Remove properties**
563   Removing properties is a little more tricky - you need to make sure that
564   the property is no longer used in the `web interface`_ *or* by the
565   detectors_.
569 Classes and Properties - creating a new information store
570 ---------------------------------------------------------
572 In the tracker above, we've defined 7 classes of information:
574   priority
575       Defines the possible levels of urgency for issues.
577   status
578       Defines the possible states of processing the issue may be in.
580   keyword
581       Initially empty, will hold keywords useful for searching issues.
583   user
584       Initially holding the "admin" user, will eventually have an entry
585       for all users using roundup.
587   msg
588       Initially empty, will hold all e-mail messages sent to or
589       generated by roundup.
591   file
592       Initially empty, will hold all files attached to issues.
594   issue
595       Initially empty, this is where the issue information is stored.
597 We define the "priority" and "status" classes to allow two things:
598 reduction in the amount of information stored on the issue and more
599 powerful, accurate searching of issues by priority and status. By only
600 requiring a link on the issue (which is stored as a single number) we
601 reduce the chance that someone mis-types a priority or status - or
602 simply makes a new one up.
605 Class and Items
606 ~~~~~~~~~~~~~~~
608 A Class defines a particular class (or type) of data that will be stored
609 in the database. A class comprises one or more properties, which gives
610 the information about the class items.
612 The actual data entered into the database, using ``class.create()``, are
613 called items. They have a special immutable property called ``'id'``. We
614 sometimes refer to this as the *itemid*.
617 Properties
618 ~~~~~~~~~~
620 A Class is comprised of one or more properties of the following types:
622 * String properties are for storing arbitrary-length strings.
623 * Password properties are for storing encoded arbitrary-length strings.
624   The default encoding is defined on the ``roundup.password.Password``
625   class.
626 * Date properties store date-and-time stamps. Their values are Timestamp
627   objects.
628 * Number properties store numeric values.
629 * Boolean properties store on/off, yes/no, true/false values.
630 * A Link property refers to a single other item selected from a
631   specified class. The class is part of the property; the value is an
632   integer, the id of the chosen item.
633 * A Multilink property refers to possibly many items in a specified
634   class. The value is a list of integers.
636 All Classes automatically have a number of properties by default:
638 *creator*
639   Link to the user that created the item.
640 *creation*
641   Date the item was created.
642 *actor*
643   Link to the user that last modified the item.
644 *activity*
645   Date the item was last modified.
648 FileClass
649 ~~~~~~~~~
651 FileClasses save their "content" attribute off in a separate file from
652 the rest of the database. This reduces the number of large entries in
653 the database, which generally makes databases more efficient, and also
654 allows us to use command-line tools to operate on the files. They are
655 stored in the files sub-directory of the ``'db'`` directory in your
656 tracker. FileClasses also have a "type" attribute to store the MIME
657 type of the file.
660 IssueClass
661 ~~~~~~~~~~
663 IssueClasses automatically include the "messages", "files", "nosy", and
664 "superseder" properties.
666 The messages and files properties list the links to the messages and
667 files related to the issue. The nosy property is a list of links to
668 users who wish to be informed of changes to the issue - they get "CC'ed"
669 e-mails when messages are sent to or generated by the issue. The nosy
670 reactor (in the ``'detectors'`` directory) handles this action. The
671 superseder link indicates an issue which has superseded this one.
673 They also have the dynamically generated "creation", "activity" and
674 "creator" properties.
676 The value of the "creation" property is the date when an item was
677 created, and the value of the "activity" property is the date when any
678 property on the item was last edited (equivalently, these are the dates
679 on the first and last records in the item's journal). The "creator"
680 property holds a link to the user that created the issue.
683 setkey(property)
684 ~~~~~~~~~~~~~~~~
686 Select a String property of the class to be the key property. The key
687 property must be unique, and allows references to the items in the class
688 by the content of the key property. That is, we can refer to users by
689 their username: for example, let's say that there's an issue in roundup,
690 issue 23. There's also a user, richard, who happens to be user 2. To
691 assign an issue to him, we could do either of::
693      roundup-admin set issue23 assignedto=2
695 or::
697      roundup-admin set issue23 assignedto=richard
699 Note, the same thing can be done in the web and e-mail interfaces. 
701 setlabelprop(property)
702 ~~~~~~~~~~~~~~~~~~~~~~
704 Select a property of the class to be the label property. The label
705 property is used whereever an item should be uniquely identified, e.g.,
706 when displaying a link to an item. If setlabelprop is not specified for
707 a class, the following values are tried for the label: 
709  * the key of the class (see the `setkey(property)`_ section above)
710  * the "name" property
711  * the "title" property
712  * the first property from the sorted property name list
714 So in most cases you can get away without specifying setlabelprop
715 explicitly.
717 setorderprop(property)
718 ~~~~~~~~~~~~~~~~~~~~~~
720 Select a property of the class to be the order property. The order
721 property is used whenever using a default sort order for the class,
722 e.g., when grouping or sorting class A by a link to class B in the user
723 interface, the order property of class B is used for sorting.  If
724 setorderprop is not specified for a class, the following values are tried
725 for the order property:
727  * the property named "order"
728  * the label property (see `setlabelprop(property)`_ above)
730 So in most cases you can get away without specifying setorderprop
731 explicitly.
733 create(information)
734 ~~~~~~~~~~~~~~~~~~~
736 Create an item in the database. This is generally used to create items
737 in the "definitional" classes like "priority" and "status".
740 A note about ordering
741 ~~~~~~~~~~~~~~~~~~~~~
743 When we sort items in the hyperdb, we use one of a number of methods,
744 depending on the properties being sorted on:
746 1. If it's a String, Number, Date or Interval property, we just sort the
747    scalar value of the property. Strings are sorted case-sensitively.
748 2. If it's a Link property, we sort by either the linked item's "order"
749    property (if it has one) or the linked item's "id".
750 3. Mulitlinks sort similar to #2, but we start with the first Multilink
751    list item, and if they're the same, we sort by the second item, and
752    so on.
754 Note that if an "order" property is defined on a Class that is used for
755 sorting, all items of that Class *must* have a value against the "order"
756 property, or sorting will result in random ordering.
759 Examples of adding to your schema
760 ---------------------------------
762 The Roundup wiki has examples of how schemas can be customised to add
763 new functionality.
766 Detectors - adding behaviour to your tracker
767 ============================================
768 .. _detectors:
770 Detectors are initialised every time you open your tracker database, so
771 you're free to add and remove them any time, even after the database is
772 initialised via the ``roundup-admin initialise`` command.
774 The detectors in your tracker fire *before* (**auditors**) and *after*
775 (**reactors**) changes to the contents of your database. They are Python
776 modules that sit in your tracker's ``detectors`` directory. You will
777 have some installed by default - have a look. You can write new
778 detectors or modify the existing ones. The existing detectors installed
779 for you are:
781 **nosyreaction.py**
782   This provides the automatic nosy list maintenance and email sending.
783   The nosy reactor (``nosyreaction``) fires when new messages are added
784   to issues. The nosy auditor (``updatenosy``) fires when issues are
785   changed, and figures out what changes need to be made to the nosy list
786   (such as adding new authors, etc.)
787 **statusauditor.py**
788   This provides the ``chatty`` auditor which changes the issue status
789   from ``unread`` or ``closed`` to ``chatting`` if new messages appear.
790   It also provides the ``presetunread`` auditor which pre-sets the
791   status to ``unread`` on new items if the status isn't explicitly
792   defined.
793 **messagesummary.py**
794   Generates the ``summary`` property for new messages based on the message
795   content.
796 **userauditor.py**
797   Verifies the content of some of the user fields (email addresses and
798   roles lists).
800 If you don't want this default behaviour, you're completely free to change
801 or remove these detectors.
803 See the detectors section in the `design document`__ for details of the
804 interface for detectors.
806 __ design.html
809 Detector API
810 ------------
812 Auditors are called with the arguments::
814     audit(db, cl, itemid, newdata)
816 where ``db`` is the database, ``cl`` is an instance of Class or
817 IssueClass within the database, and ``newdata`` is a dictionary mapping
818 property names to values.
820 For a ``create()`` operation, the ``itemid`` argument is None and
821 newdata contains all of the initial property values with which the item
822 is about to be created.
824 For a ``set()`` operation, newdata contains only the names and values of
825 properties that are about to be changed.
827 For a ``retire()`` or ``restore()`` operation, newdata is None.
829 Reactors are called with the arguments::
831     react(db, cl, itemid, olddata)
833 where ``db`` is the database, ``cl`` is an instance of Class or
834 IssueClass within the database, and ``olddata`` is a dictionary mapping
835 property names to values.
837 For a ``create()`` operation, the ``itemid`` argument is the id of the
838 newly-created item and ``olddata`` is None.
840 For a ``set()`` operation, ``olddata`` contains the names and previous
841 values of properties that were changed.
843 For a ``retire()`` or ``restore()`` operation, ``itemid`` is the id of
844 the retired or restored item and ``olddata`` is None.
847 Additional Detectors Ready For Use
848 ----------------------------------
850 Sample additional detectors that have been found useful will appear in
851 the ``'detectors'`` directory of the Roundup distribution. If you want
852 to use one, copy it to the ``'detectors'`` of your tracker instance:
854 **newissuecopy.py**
855   This detector sends an email to a team address whenever a new issue is
856   created. The address is hard-coded into the detector, so edit it
857   before you use it (look for the text 'team@team.host') or you'll get
858   email errors!
859 **creator_resolution.py**
860   Catch attempts to set the status to "resolved" - if the assignedto
861   user isn't the creator, then set the status to "confirm-done". Note that
862   "classic" Roundup doesn't have that status, so you'll have to add it. If
863   you don't want to though, it'll just use "in-progress" instead.
864 **email_auditor.py**
865   If a file added to an issue is of type message/rfc822, we tack on the
866   extension .eml.
867   The reason for this is that Microsoft Internet Explorer will not open
868   things with a .eml attachment, as they deem it 'unsafe'. Worse yet,
869   they'll just give you an incomprehensible error message. For more 
870   information, see the detector code - it has a length explanation.
873 Auditor or Reactor?
874 -------------------
876 Generally speaking, the following rules should be observed:
878 **Auditors**
879   Are used for `vetoing creation of or changes to items`_. They might
880   also make automatic changes to item properties.
881 **Reactors**
882   Detect changes in the database and react accordingly. They should avoid
883   making changes to the database where possible, as this could create
884   detector loops.
887 Vetoing creation of or changes to items
888 ---------------------------------------
890 Auditors may raise the ``Reject`` exception to prevent the creation of
891 or changes to items in the database.  The mail gateway, for example, will
892 not attach files or messages to issues when the creation of those files or
893 messages are prevented through the ``Reject`` exception. It'll also not create
894 users if that creation is ``Reject``'ed too.
896 To use, simply add at the top of your auditor::
898    from roundup.exceptions import Reject
900 And then when your rejection criteria have been detected, simply::
902    raise Reject
905 Generating email from Roundup
906 -----------------------------
908 The module ``roundup.mailer`` contains most of the nuts-n-bolts required
909 to generate email messages from Roundup.
911 In addition, the ``IssueClass`` methods ``nosymessage()`` and
912 ``send_message()`` are used to generate nosy messages, and may generate
913 messages which only consist of a change note (ie. the message id parameter
914 is not required - this is referred to as a "System Message" because it
915 comes from "the system" and not a user).
918 Database Content
919 ================
921 .. note::
922    If you modify the content of definitional classes, you'll most
923    likely need to edit the tracker `detectors`_ to reflect your changes.
925 Customisation of the special "definitional" classes (eg. status,
926 priority, resolution, ...) may be done either before or after the
927 tracker is initialised. The actual method of doing so is completely
928 different in each case though, so be careful to use the right one.
930 **Changing content before tracker initialisation**
931     Edit the initial_data.py module in your tracker to alter the items
932     created using the ``create( ... )`` methods.
934 **Changing content after tracker initialisation**
935     As the "admin" user, click on the "class list" link in the web
936     interface to bring up a list of all database classes. Click on the
937     name of the class you wish to change the content of.
939     You may also use the ``roundup-admin`` interface's create, set and
940     retire methods to add, alter or remove items from the classes in
941     question.
943 See "`adding a new field to the classic schema`_" for an example that
944 requires database content changes.
947 Security / Access Controls
948 ==========================
950 A set of Permissions is built into the security module by default:
952 - Create (everything)
953 - Edit (everything)
954 - View (everything)
956 These are assigned to the "Admin" Role by default, and allow a user to do
957 anything. Every Class you define in your `tracker schema`_ also gets an
958 Create, Edit and View Permission of its own. The web and email interfaces
959 also define:
961 *Email Access*
962   If defined, the user may use the email interface. Used by default to deny
963   Anonymous users access to the email interface. When granted to the
964   Anonymous user, they will be automatically registered by the email
965   interface (see also the ``new_email_user_roles`` configuration option).
966 *Web Access*
967   If defined, the user may use the web interface. All users are able to see
968   the login form, regardless of this setting (thus enabling logging in).
969 *Web Roles*
970   Controls user access to editing the "roles" property of the "user" class.
971   TODO: deprecate in favour of a property-based control.
973 These are hooked into the default Roles:
975 - Admin (Create, Edit, View and everything; Web Roles)
976 - User (Web Access; Email Access)
977 - Anonymous (Web Access)
979 And finally, the "admin" user gets the "Admin" Role, and the "anonymous"
980 user gets "Anonymous" assigned when the tracker is installed.
982 For the "User" Role, the "classic" tracker defines:
984 - Create, Edit and View issue, file, msg, query, keyword 
985 - View priority, status
986 - View user
987 - Edit their own user record
989 And the "Anonymous" Role is defined as:
991 - Web interface access
992 - Create user (for registration)
993 - View issue, file, msg, query, keyword, priority, status
995 Put together, these settings appear in the tracker's ``schema.py`` file::
997     #
998     # TRACKER SECURITY SETTINGS
999     #
1000     # See the configuration and customisation document for information
1001     # about security setup.
1003     #
1004     # REGULAR USERS
1005     #
1006     # Give the regular users access to the web and email interface
1007     db.security.addPermissionToRole('User', 'Web Access')
1008     db.security.addPermissionToRole('User', 'Email Access')
1010     # Assign the access and edit Permissions for issue, file and message
1011     # to regular users now
1012     for cl in 'issue', 'file', 'msg', 'query', 'keyword':
1013         db.security.addPermissionToRole('User', 'View', cl)
1014         db.security.addPermissionToRole('User', 'Edit', cl)
1015         db.security.addPermissionToRole('User', 'Create', cl)
1016     for cl in 'priority', 'status':
1017         db.security.addPermissionToRole('User', 'View', cl)
1019     # May users view other user information? Comment these lines out
1020     # if you don't want them to
1021     db.security.addPermissionToRole('User', 'View', 'user')
1023     # Users should be able to edit their own details -- this permission
1024     # is limited to only the situation where the Viewed or Edited item
1025     # is their own.
1026     def own_record(db, userid, itemid):
1027         '''Determine whether the userid matches the item being accessed.'''
1028         return userid == itemid
1029     p = db.security.addPermission(name='View', klass='user', check=own_record,
1030         description="User is allowed to view their own user details")
1031     db.security.addPermissionToRole('User', p)
1032     p = db.security.addPermission(name='Edit', klass='user', check=own_record,
1033         description="User is allowed to edit their own user details")
1034     db.security.addPermissionToRole('User', p)
1036     #
1037     # ANONYMOUS USER PERMISSIONS
1038     #
1039     # Let anonymous users access the web interface. Note that almost all
1040     # trackers will need this Permission. The only situation where it's not
1041     # required is in a tracker that uses an HTTP Basic Authenticated front-end.
1042     db.security.addPermissionToRole('Anonymous', 'Web Access')
1044     # Let anonymous users access the email interface (note that this implies
1045     # that they will be registered automatically, hence they will need the
1046     # "Create" user Permission below)
1047     # This is disabled by default to stop spam from auto-registering users on
1048     # public trackers.
1049     #db.security.addPermissionToRole('Anonymous', 'Email Access')
1051     # Assign the appropriate permissions to the anonymous user's Anonymous
1052     # Role. Choices here are:
1053     # - Allow anonymous users to register
1054     db.security.addPermissionToRole('Anonymous', 'Create', 'user')
1056     # Allow anonymous users access to view issues (and the related, linked
1057     # information)
1058     for cl in 'issue', 'file', 'msg', 'keyword', 'priority', 'status':
1059         db.security.addPermissionToRole('Anonymous', 'View', cl)
1061     # [OPTIONAL]
1062     # Allow anonymous users access to create or edit "issue" items (and the
1063     # related file and message items)
1064     #for cl in 'issue', 'file', 'msg':
1065     #   db.security.addPermissionToRole('Anonymous', 'Create', cl)
1066     #   db.security.addPermissionToRole('Anonymous', 'Edit', cl)
1069 Automatic Permission Checks
1070 ---------------------------
1072 Permissions are automatically checked when information is rendered
1073 through the web. This includes:
1075 1. View checks for properties when being rendered via the ``plain()`` or
1076    similar methods. If the check fails, the text "[hidden]" will be
1077    displayed.
1078 2. Edit checks for properties when the edit field is being rendered via
1079    the ``field()`` or similar methods. If the check fails, the property
1080    will be rendered via the ``plain()`` method (see point 1. for subsequent
1081    checking performed)
1082 3. View checks are performed in index pages for each item being displayed
1083    such that if the user does not have permission, the row is not rendered.
1084 4. View checks are performed at the top of item pages for the Item being
1085    displayed. If the user does not have permission, the text "You are not
1086    allowed to view this page." will be displayed.
1087 5. View checks are performed at the top of index pages for the Class being
1088    displayed. If the user does not have permission, the text "You are not
1089    allowed to view this page." will be displayed.
1092 New User Roles
1093 --------------
1095 New users are assigned the Roles defined in the config file as:
1097 - NEW_WEB_USER_ROLES
1098 - NEW_EMAIL_USER_ROLES
1100 The `users may only edit their issues`_ example shows customisation of
1101 these parameters.
1104 Changing Access Controls
1105 ------------------------
1107 You may alter the configuration variables to change the Role that new
1108 web or email users get, for example to not give them access to the web
1109 interface if they register through email. 
1111 You may use the ``roundup-admin`` "``security``" command to display the
1112 current Role and Permission configuration in your tracker.
1115 Adding a new Permission
1116 ~~~~~~~~~~~~~~~~~~~~~~~
1118 When adding a new Permission, you will need to:
1120 1. add it to your tracker's ``schema.py`` so it is created, using
1121    ``security.addPermission``, for example::
1123     self.security.addPermission(name="View", klass='frozzle',
1124         description="User is allowed to access frozzles")
1126    will set up a new "View" permission on the Class "frozzle".
1127 2. enable it for the Roles that should have it (verify with
1128    "``roundup-admin security``")
1129 3. add it to the relevant HTML interface templates
1130 4. add it to the appropriate xxxPermission methods on in your tracker
1131    interfaces module
1133 The ``addPermission`` method takes a couple of optional parameters:
1135 **properties**
1136   A sequence of property names that are the only properties to apply the
1137   new Permission to (eg. ``... klass='user', properties=('name',
1138   'email') ...``)
1139 **check**
1140   A function to be execute which returns boolean determining whether the
1141   Permission is allowed. The function has the signature ``check(db, userid,
1142   itemid)`` where ``db`` is a handle on the open database, ``userid`` is
1143   the user attempting access and ``itemid`` is the specific item being
1144   accessed.
1146 Example Scenarios
1147 ~~~~~~~~~~~~~~~~~
1149 See the `examples`_ section for longer examples of customisation.
1151 **anonymous access through the e-mail gateway**
1152  Give the "anonymous" user the "Email Access", ("Edit", "issue") and
1153  ("Create", "msg") Permissions but do not not give them the ("Create",
1154  "user") Permission. This means that when an unknown user sends email
1155  into the tracker, they're automatically logged in as "anonymous".
1156  Since they don't have the ("Create", "user") Permission, they won't
1157  be automatically registered, but since "anonymous" has permission to
1158  use the gateway, they'll still be able to submit issues. Note that
1159  the Sender information - their email address - will not be available
1160  - they're *anonymous*.
1162 **automatic registration of users in the e-mail gateway**
1163  By giving the "anonymous" user the ("Create", "user") Permission, any
1164  unidentified user will automatically be registered with the tracker
1165  (with no password, so they won't be able to log in through
1166  the web until an admin sets their password). By default new Roundup
1167  trackers don't allow this as it opens them up to spam. It may be enabled
1168  by uncommenting the appropriate addPermissionToRole in your tracker's
1169  ``schema.py`` file. The new user is given the Roles list defined in the
1170  "new_email_user_roles" config variable. 
1172 **only developers may be assigned issues**
1173  Create a new Permission called "Fixer" for the "issue" class. Create a
1174  new Role "Developer" which has that Permission, and assign that to the
1175  appropriate users. Filter the list of users available in the assignedto
1176  list to include only those users. Enforce the Permission with an
1177  auditor. See the example 
1178  `restricting the list of users that are assignable to a task`_.
1180 **only managers may sign off issues as complete**
1181  Create a new Permission called "Closer" for the "issue" class. Create a
1182  new Role "Manager" which has that Permission, and assign that to the
1183  appropriate users. In your web interface, only display the "resolved"
1184  issue state option when the user has the "Closer" Permissions. Enforce
1185  the Permission with an auditor. This is very similar to the previous
1186  example, except that the web interface check would look like::
1188    <option tal:condition="python:request.user.hasPermission('Closer')"
1189            value="resolved">Resolved</option>
1190  
1191 **don't give web access to users who register through email**
1192  Create a new Role called "Email User" which has all the Permissions of
1193  the normal "User" Role minus the "Web Access" Permission. This will
1194  allow users to send in emails to the tracker, but not access the web
1195  interface.
1197 **let some users edit the details of all users**
1198  Create a new Role called "User Admin" which has the Permission for
1199  editing users::
1201     db.security.addRole(name='User Admin', description='Managing users')
1202     p = db.security.getPermission('Edit', 'user')
1203     db.security.addPermissionToRole('User Admin', p)
1205  and assign the Role to the users who need the permission.
1208 Web Interface
1209 =============
1211 .. contents::
1212    :local:
1214 The web interface is provided by the ``roundup.cgi.client`` module and
1215 is used by ``roundup.cgi``, ``roundup-server`` and ``ZRoundup``
1216 (``ZRoundup``  is broken, until further notice). In all cases, we
1217 determine which tracker is being accessed (the first part of the URL
1218 path inside the scope of the CGI handler) and pass control on to the
1219 ``roundup.cgi.client.Client`` class - which handles the rest of the
1220 access through its ``main()`` method. This means that you can do pretty
1221 much anything you want as a web interface to your tracker.
1225 Repercussions of changing the tracker schema
1226 ---------------------------------------------
1228 If you choose to change the `tracker schema`_ you will need to ensure
1229 the web interface knows about it:
1231 1. Index, item and search pages for the relevant classes may need to
1232    have properties added or removed,
1233 2. The "page" template may require links to be changed, as might the
1234    "home" page's content arguments.
1237 How requests are processed
1238 --------------------------
1240 The basic processing of a web request proceeds as follows:
1242 1. figure out who we are, defaulting to the "anonymous" user
1243 2. figure out what the request is for - we call this the "context"
1244 3. handle any requested action (item edit, search, ...)
1245 4. render the template requested by the context, resulting in HTML
1246    output
1248 In some situations, exceptions occur:
1250 - HTTP Redirect  (generally raised by an action)
1251 - SendFile       (generally raised by ``determine_context``)
1252     here we serve up a FileClass "content" property
1253 - SendStaticFile (generally raised by ``determine_context``)
1254     here we serve up a file from the tracker "html" directory
1255 - Unauthorised   (generally raised by an action)
1256     here the action is cancelled, the request is rendered and an error
1257     message is displayed indicating that permission was not granted for
1258     the action to take place
1259 - NotFound       (raised wherever it needs to be)
1260     this exception percolates up to the CGI interface that called the
1261     client
1264 Determining web context
1265 -----------------------
1267 To determine the "context" of a request, we look at the URL and the
1268 special request variable ``@template``. The URL path after the tracker
1269 identifier is examined. Typical URL paths look like:
1271 1.  ``/tracker/issue``
1272 2.  ``/tracker/issue1``
1273 3.  ``/tracker/@@file/style.css``
1274 4.  ``/cgi-bin/roundup.cgi/tracker/file1``
1275 5.  ``/cgi-bin/roundup.cgi/tracker/file1/kitten.png``
1277 where the "tracker identifier" is "tracker" in the above cases. That means
1278 we're looking at "issue", "issue1", "@@file/style.css", "file1" and
1279 "file1/kitten.png" in the cases above. The path is generally only one
1280 entry long - longer paths are handled differently.
1282 a. if there is no path, then we are in the "home" context. See `the "home"
1283    context`_ below for more information about how it may be used.
1284 b. if the path starts with "@@file" (as in example 3,
1285    "/tracker/@@file/style.css"), then the additional path entry,
1286    "style.css" specifies the filename of a static file we're to serve up
1287    from the tracker TEMPLATES (or STATIC_FILES, if configured) directory.
1288    This is usually the tracker's "html" directory. Raises a SendStaticFile
1289    exception.
1290 c. if there is something in the path (as in example 1, "issue"), it
1291    identifies the tracker class we're to display.
1292 d. if the path is an item designator (as in examples 2 and 4, "issue1"
1293    and "file1"), then we're to display a specific item.
1294 e. if the path starts with an item designator and is longer than one
1295    entry (as in example 5, "file1/kitten.png"), then we're assumed to be
1296    handling an item of a ``FileClass``, and the extra path information
1297    gives the filename that the client is going to label the download
1298    with (i.e. "file1/kitten.png" is nicer to download than "file1").
1299    This raises a ``SendFile`` exception.
1301 Both b. and e. stop before we bother to determine the template we're
1302 going to use. That's because they don't actually use templates.
1304 The template used is specified by the ``@template`` CGI variable, which
1305 defaults to:
1307 - only classname suplied:        "index"
1308 - full item designator supplied: "item"
1311 The "home" Context
1312 ------------------
1314 The "home" context is special because it allows you to add templated
1315 pages to your tracker that don't rely on a class or item (ie. an issues
1316 list or specific issue).
1318 Let's say you wish to add frames to control the layout of your tracker's
1319 interface. You'd probably have:
1321 - A top-level frameset page. This page probably wouldn't be templated, so
1322   it could be served as a static file (see `serving static content`_)
1323 - A sidebar frame that is templated. Let's call this page
1324   "home.navigation.html" in your tracker's "html" directory. To load that
1325   page up, you use the URL:
1327     <tracker url>/home?@template=navigation
1330 Serving static content
1331 ----------------------
1333 See the previous section `determining web context`_ where it describes
1334 ``@@file`` paths.
1337 Performing actions in web requests
1338 ----------------------------------
1340 When a user requests a web page, they may optionally also request for an
1341 action to take place. As described in `how requests are processed`_, the
1342 action is performed before the requested page is generated. Actions are
1343 triggered by using a ``@action`` CGI variable, where the value is one
1344 of:
1346 **login**
1347  Attempt to log a user in.
1349 **logout**
1350  Log the user out - make them "anonymous".
1352 **register**
1353  Attempt to create a new user based on the contents of the form and then
1354  log them in.
1356 **edit**
1357  Perform an edit of an item in the database. There are some `special form
1358  variables`_ you may use.
1360 **new**
1361  Add a new item to the database. You may use the same `special form
1362  variables`_ as in the "edit" action.
1364 **retire**
1365  Retire the item in the database.
1367 **editCSV**
1368  Performs an edit of all of a class' items in one go. See also the
1369  *class*.csv templating method which generates the CSV data to be
1370  edited, and the ``'_generic.index'`` template which uses both of these
1371  features.
1373 **search**
1374  Mangle some of the form variables:
1376  - Set the form ":filter" variable based on the values of the filter
1377    variables - if they're set to anything other than "dontcare" then add
1378    them to :filter.
1380  - Also handle the ":queryname" variable and save off the query to the
1381    user's query list.
1383 Each of the actions is implemented by a corresponding ``*XxxAction*`` (where
1384 "Xxx" is the name of the action) class in the ``roundup.cgi.actions`` module.
1385 These classes are registered with ``roundup.cgi.client.Client``. If you need
1386 to define new actions, you may add them there (see `defining new
1387 web actions`_).
1389 Each action class also has a ``*permission*`` method which determines whether
1390 the action is permissible given the current user. The base permission checks
1391 for each action are:
1393 **login**
1394  Determine whether the user has the "Web Access" Permission.
1395 **logout**
1396  No permission checks are made.
1397 **register**
1398  Determine whether the user has the ("Create", "user") Permission.
1399 **edit**
1400  Determine whether the user has permission to edit this item. If we're
1401  editing the "user" class, users are allowed to edit their own details -
1402  unless they try to edit the "roles" property, which requires the
1403  special Permission "Web Roles".
1404 **new**
1405  Determine whether the user has permission to create this item. No
1406  additional property checks are made. Additionally, new user items may
1407  be created if the user has the ("Create", "user") Permission.
1408 **editCSV**
1409  Determine whether the user has permission to edit this class.
1410 **search**
1411  Determine whether the user has permission to view this class.
1414 Special form variables
1415 ----------------------
1417 Item properties and their values are edited with html FORM
1418 variables and their values. You can:
1420 - Change the value of some property of the current item.
1421 - Create a new item of any class, and edit the new item's
1422   properties,
1423 - Attach newly created items to a multilink property of the
1424   current item.
1425 - Remove items from a multilink property of the current item.
1426 - Specify that some properties are required for the edit
1427   operation to be successful.
1428 - Set up user interface locale.
1430 These operations will only take place if the form action (the
1431 ``@action`` variable) is "edit" or "new".
1433 In the following, <bracketed> values are variable, "@" may be
1434 either ":" or "@", and other text "required" is fixed.
1436 Two special form variables are used to specify user language preferences:
1438 ``@language``
1439   value may be locale name or ``none``. If this variable is set to
1440   locale name, web interface language is changed to given value
1441   (provided that appropriate translation is available), the value
1442   is stored in the browser cookie and will be used for all following
1443   requests.  If value is ``none`` the cookie is removed and the
1444   language is changed to the tracker default, set up in the tracker
1445   configuration or OS environment.
1447 ``@charset``
1448   value may be character set name or ``none``.  Character set name
1449   is stored in the browser cookie and sets output encoding for all
1450   HTML pages generated by Roundup.  If value is ``none`` the cookie
1451   is removed and HTML output is reset to Roundup internal encoding
1452   (UTF-8).
1454 Most properties are specified as form variables:
1456 ``<propname>``
1457   property on the current context item
1459 ``<designator>"@"<propname>``
1460   property on the indicated item (for editing related information)
1462 Designators name a specific item of a class.
1464 ``<classname><N>``
1465     Name an existing item of class <classname>.
1467 ``<classname>"-"<N>``
1468     Name the <N>th new item of class <classname>. If the form
1469     submission is successful, a new item of <classname> is
1470     created. Within the submitted form, a particular
1471     designator of this form always refers to the same new
1472     item.
1474 Once we have determined the "propname", we look at it to see
1475 if it's special:
1477 ``@required``
1478     The associated form value is a comma-separated list of
1479     property names that must be specified when the form is
1480     submitted for the edit operation to succeed.  
1482     When the <designator> is missing, the properties are
1483     for the current context item.  When <designator> is
1484     present, they are for the item specified by
1485     <designator>.
1487     The "@required" specifier must come before any of the
1488     properties it refers to are assigned in the form.
1490 ``@remove@<propname>=id(s)`` or ``@add@<propname>=id(s)``
1491     The "@add@" and "@remove@" edit actions apply only to
1492     Multilink properties.  The form value must be a
1493     comma-separate list of keys for the class specified by
1494     the simple form variable.  The listed items are added
1495     to (respectively, removed from) the specified
1496     property.
1498 ``@link@<propname>=<designator>``
1499     If the edit action is "@link@", the simple form
1500     variable must specify a Link or Multilink property.
1501     The form value is a comma-separated list of
1502     designators.  The item corresponding to each
1503     designator is linked to the property given by simple
1504     form variable.
1506 None of the above (ie. just a simple form value)
1507     The value of the form variable is converted
1508     appropriately, depending on the type of the property.
1510     For a Link('klass') property, the form value is a
1511     single key for 'klass', where the key field is
1512     specified in schema.py.  
1514     For a Multilink('klass') property, the form value is a
1515     comma-separated list of keys for 'klass', where the
1516     key field is specified in schema.py.  
1518     Note that for simple-form-variables specifiying Link
1519     and Multilink properties, the linked-to class must
1520     have a key field.
1522     For a String() property specifying a filename, the
1523     file named by the form value is uploaded. This means we
1524     try to set additional properties "filename" and "type" (if
1525     they are valid for the class).  Otherwise, the property
1526     is set to the form value.
1528     For Date(), Interval(), Boolean(), and Number()
1529     properties, the form value is converted to the
1530     appropriate
1532 Any of the form variables may be prefixed with a classname or
1533 designator.
1535 Two special form values are supported for backwards compatibility:
1537 @note
1538     This is equivalent to::
1540         @link@messages=msg-1
1541         msg-1@content=value
1543     except that in addition, the "author" and "date" properties of
1544     "msg-1" are set to the userid of the submitter, and the current
1545     time, respectively.
1547 @file
1548     This is equivalent to::
1550         @link@files=file-1
1551         file-1@content=value
1553     The String content value is handled as described above for file
1554     uploads.
1556 If both the "@note" and "@file" form variables are
1557 specified, the action::
1559         @link@msg-1@files=file-1
1561 is also performed.
1563 We also check that FileClass items have a "content" property with
1564 actual content, otherwise we remove them from all_props before
1565 returning.
1568 Default templates
1569 -----------------
1571 The default templates are html4 compliant. If you wish to change them to be
1572 xhtml compliant, you'll need to change the ``html_version`` configuration
1573 variable in ``config.ini`` to ``'xhtml'`` instead of ``'html4'``.
1575 Most customisation of the web view can be done by modifying the
1576 templates in the tracker ``'html'`` directory. There are several types
1577 of files in there. The *minimal* template includes:
1579 **page.html**
1580   This template usually defines the overall look of your tracker. When
1581   you view an issue, it appears inside this template. When you view an
1582   index, it also appears inside this template. This template defines a
1583   macro called "icing" which is used by almost all other templates as a
1584   coating for their content, using its "content" slot. It also defines
1585   the "head_title" and "body_title" slots to allow setting of the page
1586   title.
1587 **home.html**
1588   the default page displayed when no other page is indicated by the user
1589 **home.classlist.html**
1590   a special version of the default page that lists the classes in the
1591   tracker
1592 **classname.item.html**
1593   displays an item of the *classname* class
1594 **classname.index.html**
1595   displays a list of *classname* items
1596 **classname.search.html**
1597   displays a search page for *classname* items
1598 **_generic.index.html**
1599   used to display a list of items where there is no
1600   ``*classname*.index`` available
1601 **_generic.help.html**
1602   used to display a "class help" page where there is no
1603   ``*classname*.help``
1604 **user.register.html**
1605   a special page just for the user class, that renders the registration
1606   page
1607 **style.css.html**
1608   a static file that is served up as-is
1610 The *classic* template has a number of additional templates.
1612 Remember that you can create any template extension you want to,
1613 so if you just want to play around with the templating for new issues,
1614 you can copy the current "issue.item" template to "issue.test", and then
1615 access the test template using the "@template" URL argument::
1617    http://your.tracker.example/tracker/issue?@template=test
1619 and it won't affect your users using the "issue.item" template.
1622 How the templates work
1623 ----------------------
1626 Basic Templating Actions
1627 ~~~~~~~~~~~~~~~~~~~~~~~~
1629 Roundup's templates consist of special attributes on the HTML tags.
1630 These attributes form the `Template Attribute Language`_, or TAL.
1631 The basic TAL commands are:
1633 **tal:define="variable expression; variable expression; ..."**
1634    Define a new variable that is local to this tag and its contents. For
1635    example::
1637       <html tal:define="title request/description">
1638        <head><title tal:content="title"></title></head>
1639       </html>
1641    In this example, the variable "title" is defined as the result of the
1642    expression "request/description". The "tal:content" command inside the
1643    <html> tag may then use the "title" variable.
1645 **tal:condition="expression"**
1646    Only keep this tag and its contents if the expression is true. For
1647    example::
1649      <p tal:condition="python:request.user.hasPermission('View', 'issue')">
1650       Display some issue information.
1651      </p>
1653    In the example, the <p> tag and its contents are only displayed if
1654    the user has the "View" permission for issues. We consider the number
1655    zero, a blank string, an empty list, and the built-in variable
1656    nothing to be false values. Nearly every other value is true,
1657    including non-zero numbers, and strings with anything in them (even
1658    spaces!).
1660 **tal:repeat="variable expression"**
1661    Repeat this tag and its contents for each element of the sequence
1662    that the expression returns, defining a new local variable and a
1663    special "repeat" variable for each element. For example::
1665      <tr tal:repeat="u user/list">
1666       <td tal:content="u/id"></td>
1667       <td tal:content="u/username"></td>
1668       <td tal:content="u/realname"></td>
1669      </tr>
1671    The example would iterate over the sequence of users returned by
1672    "user/list" and define the local variable "u" for each entry. Using
1673    the repeat command creates a new variable called "repeat" which you
1674    may access to gather information about the iteration. See the section
1675    below on `the repeat variable`_.
1677 **tal:replace="expression"**
1678    Replace this tag with the result of the expression. For example::
1680     <span tal:replace="request/user/realname" />
1682    The example would replace the <span> tag and its contents with the
1683    user's realname. If the user's realname was "Bruce", then the
1684    resultant output would be "Bruce".
1686 **tal:content="expression"**
1687    Replace the contents of this tag with the result of the expression.
1688    For example::
1690     <span tal:content="request/user/realname">user's name appears here
1691     </span>
1693    The example would replace the contents of the <span> tag with the
1694    user's realname. If the user's realname was "Bruce" then the
1695    resultant output would be "<span>Bruce</span>".
1697 **tal:attributes="attribute expression; attribute expression; ..."**
1698    Set attributes on this tag to the results of expressions. For
1699    example::
1701      <a tal:attributes="href string:user${request/user/id}">My Details</a>
1703    In the example, the "href" attribute of the <a> tag is set to the
1704    value of the "string:user${request/user/id}" expression, which will
1705    be something like "user123".
1707 **tal:omit-tag="expression"**
1708    Remove this tag (but not its contents) if the expression is true. For
1709    example::
1711       <span tal:omit-tag="python:1">Hello, world!</span>
1713    would result in output of::
1715       Hello, world!
1717 Note that the commands on a given tag are evaulated in the order above,
1718 so *define* comes before *condition*, and so on.
1720 Additionally, you may include tags such as <tal:block>, which are
1721 removed from output. Its content is kept, but the tag itself is not (so
1722 don't go using any "tal:attributes" commands on it). This is useful for
1723 making arbitrary blocks of HTML conditional or repeatable (very handy
1724 for repeating multiple table rows, which would othewise require an
1725 illegal tag placement to effect the repeat).
1727 .. _TAL:
1728 .. _Template Attribute Language:
1729    http://dev.zope.org/Wikis/DevSite/Projects/ZPT/TAL%20Specification%201.4
1732 Templating Expressions
1733 ~~~~~~~~~~~~~~~~~~~~~~
1735 Templating Expressions are covered by `Template Attribute Language
1736 Expression Syntax`_, or TALES. The expressions you may use in the
1737 attribute values may be one of the following forms:
1739 **Path Expressions** - eg. ``item/status/checklist``
1740    These are object attribute / item accesses. Roughly speaking, the
1741    path ``item/status/checklist`` is broken into parts ``item``,
1742    ``status`` and ``checklist``. The ``item`` part is the root of the
1743    expression. We then look for a ``status`` attribute on ``item``, or
1744    failing that, a ``status`` item (as in ``item['status']``). If that
1745    fails, the path expression fails. When we get to the end, the object
1746    we're left with is evaluated to get a string - if it is a method, it
1747    is called; if it is an object, it is stringified. Path expressions
1748    may have an optional ``path:`` prefix, but they are the default
1749    expression type, so it's not necessary.
1751    If an expression evaluates to ``default``, then the expression is
1752    "cancelled" - whatever HTML already exists in the template will
1753    remain (tag content in the case of ``tal:content``, attributes in the
1754    case of ``tal:attributes``).
1756    If an expression evaluates to ``nothing`` then the target of the
1757    expression is removed (tag content in the case of ``tal:content``,
1758    attributes in the case of ``tal:attributes`` and the tag itself in
1759    the case of ``tal:replace``).
1761    If an element in the path may not exist, then you can use the ``|``
1762    operator in the expression to provide an alternative. So, the
1763    expression ``request/form/foo/value | default`` would simply leave
1764    the current HTML in place if the "foo" form variable doesn't exist.
1766    You may use the python function ``path``, as in
1767    ``path("item/status")``, to embed path expressions in Python
1768    expressions.
1770 **String Expressions** - eg. ``string:hello ${user/name}`` 
1771    These expressions are simple string interpolations - though they can
1772    be just plain strings with no interpolation if you want. The
1773    expression in the ``${ ... }`` is just a path expression as above.
1775 **Python Expressions** - eg. ``python: 1+1`` 
1776    These expressions give the full power of Python. All the "root level"
1777    variables are available, so ``python:item.status.checklist()`` would
1778    be equivalent to ``item/status/checklist``, assuming that
1779    ``checklist`` is a method.
1781 Modifiers:
1783 **structure** - eg. ``structure python:msg.content.plain(hyperlink=1)``
1784    The result of expressions are normally *escaped* to be safe for HTML
1785    display (all "<", ">" and "&" are turned into special entities). The
1786    ``structure`` expression modifier turns off this escaping - the
1787    result of the expression is now assumed to be HTML, which is passed
1788    to the web browser for rendering.
1790 **not:** - eg. ``not:python:1=1``
1791    This simply inverts the logical true/false value of another
1792    expression.
1794 .. _TALES:
1795 .. _Template Attribute Language Expression Syntax:
1796    http://dev.zope.org/Wikis/DevSite/Projects/ZPT/TALES%20Specification%201.3
1799 Template Macros
1800 ~~~~~~~~~~~~~~~
1802 Macros are used in Roundup to save us from repeating the same common
1803 page stuctures over and over. The most common (and probably only) macro
1804 you'll use is the "icing" macro defined in the "page" template.
1806 Macros are generated and used inside your templates using special
1807 attributes similar to the `basic templating actions`_. In this case,
1808 though, the attributes belong to the `Macro Expansion Template
1809 Attribute Language`_, or METAL. The macro commands are:
1811 **metal:define-macro="macro name"**
1812   Define that the tag and its contents are now a macro that may be
1813   inserted into other templates using the *use-macro* command. For
1814   example::
1816     <html metal:define-macro="page">
1817      ...
1818     </html>
1820   defines a macro called "page" using the ``<html>`` tag and its
1821   contents. Once defined, macros are stored on the template they're
1822   defined on in the ``macros`` attribute. You can access them later on
1823   through the ``templates`` variable, eg. the most common
1824   ``templates/page/macros/icing`` to access the "page" macro of the
1825   "page" template.
1827 **metal:use-macro="path expression"**
1828   Use a macro, which is identified by the path expression (see above).
1829   This will replace the current tag with the identified macro contents.
1830   For example::
1832    <tal:block metal:use-macro="templates/page/macros/icing">
1833     ...
1834    </tal:block>
1836    will replace the tag and its contents with the "page" macro of the
1837    "page" template.
1839 **metal:define-slot="slot name"** and **metal:fill-slot="slot name"**
1840   To define *dynamic* parts of the macro, you define "slots" which may
1841   be filled when the macro is used with a *use-macro* command. For
1842   example, the ``templates/page/macros/icing`` macro defines a slot like
1843   so::
1845     <title metal:define-slot="head_title">title goes here</title>
1847   In your *use-macro* command, you may now use a *fill-slot* command
1848   like this::
1850     <title metal:fill-slot="head_title">My Title</title>
1852   where the tag that fills the slot completely replaces the one defined
1853   as the slot in the macro.
1855 Note that you may not mix `METAL`_ and `TAL`_ commands on the same tag, but
1856 TAL commands may be used freely inside METAL-using tags (so your
1857 *fill-slots* tags may have all manner of TAL inside them).
1859 .. _METAL:
1860 .. _Macro Expansion Template Attribute Language:
1861    http://dev.zope.org/Wikis/DevSite/Projects/ZPT/METAL%20Specification%201.0
1863 Information available to templates
1864 ----------------------------------
1866 This is implemented by ``roundup.cgi.templating.RoundupPageTemplate``
1868 The following variables are available to templates.
1870 **context**
1871   The current context. This is either None, a `hyperdb class wrapper`_
1872   or a `hyperdb item wrapper`_
1873 **request**
1874   Includes information about the current request, including:
1875    - the current index information (``filterspec``, ``filter`` args,
1876      ``properties``, etc) parsed out of the form. 
1877    - methods for easy filterspec link generation
1878    - "form"
1879      The current CGI form information as a mapping of form argument name
1880      to value (specifically a cgi.FieldStorage)
1881    - "env" the CGI environment variables
1882    - "base" the base URL for this instance
1883    - "user" a HTMLItem instance for the current user
1884    - "language" as determined by the browser or config
1885    - "classname" the current classname (possibly None)
1886    - "template" the current template (suffix, also possibly None)
1887 **config**
1888   This variable holds all the values defined in the tracker config.ini
1889   file (eg. TRACKER_NAME, etc.)
1890 **db**
1891   The current database, used to access arbitrary database items.
1892 **templates**
1893   Access to all the tracker templates by name. Used mainly in
1894   *use-macro* commands.
1895 **utils**
1896   This variable makes available some utility functions like batching.
1897 **nothing**
1898   This is a special variable - if an expression evaluates to this, then
1899   the tag (in the case of a ``tal:replace``), its contents (in the case
1900   of ``tal:content``) or some attributes (in the case of
1901   ``tal:attributes``) will not appear in the the output. So, for
1902   example::
1904     <span tal:attributes="class nothing">Hello, World!</span>
1906   would result in::
1908     <span>Hello, World!</span>
1910 **default**
1911   Also a special variable - if an expression evaluates to this, then the
1912   existing HTML in the template will not be replaced or removed, it will
1913   remain. So::
1915     <span tal:replace="default">Hello, World!</span>
1917   would result in::
1919     <span>Hello, World!</span>
1921 **true**, **false**
1922   Boolean constants that may be used in `templating expressions`_
1923   instead of ``python:1`` and ``python:0``.
1924 **i18n**
1925   Internationalization service, providing two string translation methods:
1927   **gettext** (*message*)
1928     Return the localized translation of message
1929   **ngettext** (*singular*, *plural*, *number*)
1930     Like ``gettext()``, but consider plural forms. If a translation
1931     is found, apply the plural formula to *number*, and return the
1932     resulting message (some languages have more than two plural forms).
1933     If no translation is found, return singular if *number* is 1;
1934     return plural otherwise.
1936     This function requires python2.3; in earlier python versions
1937     may not work as expected.
1939 The context variable
1940 ~~~~~~~~~~~~~~~~~~~~
1942 The *context* variable is one of three things based on the current
1943 context (see `determining web context`_ for how we figure this out):
1945 1. if we're looking at a "home" page, then it's None
1946 2. if we're looking at a specific hyperdb class, it's a
1947    `hyperdb class wrapper`_.
1948 3. if we're looking at a specific hyperdb item, it's a
1949    `hyperdb item wrapper`_.
1951 If the context is not None, we can access the properties of the class or
1952 item. The only real difference between cases 2 and 3 above are:
1954 1. the properties may have a real value behind them, and this will
1955    appear if the property is displayed through ``context/property`` or
1956    ``context/property/field``.
1957 2. the context's "id" property will be a false value in the second case,
1958    but a real, or true value in the third. Thus we can determine whether
1959    we're looking at a real item from the hyperdb by testing
1960    "context/id".
1962 Hyperdb class wrapper
1963 :::::::::::::::::::::
1965 This is implemented by the ``roundup.cgi.templating.HTMLClass``
1966 class.
1968 This wrapper object provides access to a hyperb class. It is used
1969 primarily in both index view and new item views, but it's also usable
1970 anywhere else that you wish to access information about a class, or the
1971 items of a class, when you don't have a specific item of that class in
1972 mind.
1974 We allow access to properties. There will be no "id" property. The value
1975 accessed through the property will be the current value of the same name
1976 from the CGI form.
1978 There are several methods available on these wrapper objects:
1980 =========== =============================================================
1981 Method      Description
1982 =========== =============================================================
1983 properties  return a `hyperdb property wrapper`_ for all of this class's
1984             properties.
1985 list        lists all of the active (not retired) items in the class.
1986 csv         return the items of this class as a chunk of CSV text.
1987 propnames   lists the names of the properties of this class.
1988 filter      lists of items from this class, filtered and sorted. Two
1989             options are avaible for sorting:
1991             1. by the current *request* filterspec/filter/sort/group args
1992             2. by the "filterspec", "sort" and "group" keyword args.
1993                "filterspec" is ``{propname: value(s)}``. "sort" and
1994                "group" are an optionally empty list ``[(dir, prop)]``
1995                where dir is '+', '-' or None
1996                and prop is a prop name or None.
1998                The propname in filterspec and prop in a sort/group spec
1999                may be transitive, i.e., it may contain properties of
2000                the form link.link.link.name.
2002             eg. All issues with a priority of "1" with messages added in
2003             the last week, sorted by activity date:
2004             ``issue.filter(filterspec={"priority": "1",
2005             'messages.creation' : '.-1w;'}, sort=[('activity', '+')])``
2007 filter_sql  **Only in SQL backends**
2009             Lists the items that match the SQL provided. The SQL is a
2010             complete "select" statement.
2012             The SQL select must include the item id as the first column.
2014             This function **does not** filter out retired items, add
2015             on a where clause "__retired__ <> 1" if you don't want
2016             retired nodes.
2018 classhelp   display a link to a javascript popup containing this class'
2019             "help" template.
2021             This generates a link to a popup window which displays the
2022             properties indicated by "properties" of the class named by
2023             "classname". The "properties" should be a comma-separated list
2024             (eg. 'id,name,description'). Properties defaults to all the
2025             properties of a class (excluding id, creator, created and
2026             activity).
2028             You may optionally override the "label" displayed, the "width",
2029             the "height", the number of items per page ("pagesize") and
2030             the field on which the list is sorted ("sort").
2032             With the "filter" arg it is possible to specify a filter for
2033             which items are supposed to be displayed. It has to be of
2034             the format "<field>=<values>;<field>=<values>;...".
2036             The popup window will be resizable and scrollable.
2038             If the "property" arg is given, it's passed through to the
2039             javascript help_window function. This allows updating of a
2040             property in the calling HTML page.
2042             If the "form" arg is given, it's passed through to the
2043             javascript help_window function - it's the name of the form
2044             the "property" belongs to.
2046 submit      generate a submit button (and action hidden element)
2047 renderWith  render this class with the given template.
2048 history     returns 'New node - no history' :)
2049 is_edit_ok  is the user allowed to Edit the current class?
2050 is_view_ok  is the user allowed to View the current class?
2051 =========== =============================================================
2053 Note that if you have a property of the same name as one of the above
2054 methods, you'll need to access it using a python "item access"
2055 expression. For example::
2057    python:context['list']
2059 will access the "list" property, rather than the list method.
2062 Hyperdb item wrapper
2063 ::::::::::::::::::::
2065 This is implemented by the ``roundup.cgi.templating.HTMLItem``
2066 class.
2068 This wrapper object provides access to a hyperb item.
2070 We allow access to properties. There will be no "id" property. The value
2071 accessed through the property will be the current value of the same name
2072 from the CGI form.
2074 There are several methods available on these wrapper objects:
2076 =============== ========================================================
2077 Method          Description
2078 =============== ========================================================
2079 submit          generate a submit button (and action hidden element)
2080 journal         return the journal of the current item (**not
2081                 implemented**)
2082 history         render the journal of the current item as HTML
2083 renderQueryForm specific to the "query" class - render the search form
2084                 for the query
2085 hasPermission   specific to the "user" class - determine whether the
2086                 user has a Permission. The signature is::
2088                     hasPermission(self, permission, [classname=],
2089                         [property=], [itemid=])
2091                 where the classname defaults to the current context.
2092 hasRole         specific to the "user" class - determine whether the
2093                 user has a Role. The signature is::
2095                     hasRole(self, rolename)
2097 is_edit_ok      is the user allowed to Edit the current item?
2098 is_view_ok      is the user allowed to View the current item?
2099 is_retired      is the item retired?
2100 download_url    generate a url-quoted link for download of FileClass
2101                 item contents (ie. file<id>/<name>)
2102 copy_url        generate a url-quoted link for creating a copy
2103                 of this item.  By default, the copy will acquire
2104                 all properties of the current item except for
2105                 ``messages`` and ``files``.  This can be overridden
2106                 by passing ``exclude`` argument which contains a list
2107                 (or any iterable) of property names that shall not be
2108                 copied.  Database-driven properties like ``id`` or
2109                 ``activity`` cannot be copied.
2110 =============== ========================================================
2112 Note that if you have a property of the same name as one of the above
2113 methods, you'll need to access it using a python "item access"
2114 expression. For example::
2116    python:context['journal']
2118 will access the "journal" property, rather than the journal method.
2121 Hyperdb property wrapper
2122 ::::::::::::::::::::::::
2124 This is implemented by subclasses of the
2125 ``roundup.cgi.templating.HTMLProperty`` class (``HTMLStringProperty``,
2126 ``HTMLNumberProperty``, and so on).
2128 This wrapper object provides access to a single property of a class. Its
2129 value may be either:
2131 1. if accessed through a `hyperdb item wrapper`_, then it's a value from
2132    the hyperdb
2133 2. if access through a `hyperdb class wrapper`_, then it's a value from
2134    the CGI form
2137 The property wrapper has some useful attributes:
2139 =============== ========================================================
2140 Attribute       Description
2141 =============== ========================================================
2142 _name           the name of the property
2143 _value          the value of the property if any - this is the actual
2144                 value retrieved from the hyperdb for this property
2145 =============== ========================================================
2147 There are several methods available on these wrapper objects:
2149 =========== ================================================================
2150 Method      Description
2151 =========== ================================================================
2152 plain       render a "plain" representation of the property. This method
2153             may take two arguments:
2155             escape
2156              If true, escape the text so it is HTML safe (default: no). The
2157              reason this defaults to off is that text is usually escaped
2158              at a later stage by the TAL commands, unless the "structure"
2159              option is used in the template. The following ``tal:content``
2160              expressions are all equivalent::
2161  
2162               "structure python:msg.content.plain(escape=1)"
2163               "python:msg.content.plain()"
2164               "msg/content/plain"
2165               "msg/content"
2167              Usually you'll only want to use the escape option in a
2168              complex expression.
2170             hyperlink
2171              If true, turn URLs, email addresses and hyperdb item
2172              designators in the text into hyperlinks (default: no). Note
2173              that you'll need to use the "structure" TAL option if you
2174              want to use this ``tal:content`` expression::
2175   
2176               "structure python:msg.content.plain(hyperlink=1)"
2178              The text is automatically HTML-escaped before the hyperlinking
2179              transformation done in the plain() method.
2181 hyperlinked The same as msg.content.plain(hyperlink=1), but nicer::
2183               "structure msg/content/hyperlinked"
2185 field       render an appropriate form edit field for the property - for
2186             most types this is a text entry box, but for Booleans it's a
2187             tri-state yes/no/neither selection. This method may take some
2188             arguments:
2190             size
2191               Sets the width in characters of the edit field
2193             format (Date properties only)
2194               Sets the format of the date in the field - uses the same
2195               format string argument as supplied to the ``pretty`` method
2196               below.
2198             popcal (Date properties only)
2199               Include the Javascript-based popup calendar for date
2200               selection. Defaults to on.
2202 stext       only on String properties - render the value of the property
2203             as StructuredText (requires the StructureText module to be
2204             installed separately)
2205 multiline   only on String properties - render a multiline form edit
2206             field for the property
2207 email       only on String properties - render the value of the property
2208             as an obscured email address
2209 confirm     only on Password properties - render a second form edit field
2210             for the property, used for confirmation that the user typed
2211             the password correctly. Generates a field with name
2212             "name:confirm".
2213 now         only on Date properties - return the current date as a new
2214             property
2215 reldate     only on Date properties - render the interval between the date
2216             and now
2217 local       only on Date properties - return this date as a new property
2218             with some timezone offset, for example::
2219             
2220                 python:context.creation.local(10)
2222             will render the date with a +10 hour offset.
2223 pretty      Date properties - render the date as "dd Mon YYYY" (eg. "19
2224             Mar 2004"). Takes an optional format argument, for example::
2226                 python:context.activity.pretty('%Y-%m-%d')
2228             Will format as "2004-03-19" instead.
2230             Interval properties - render the interval in a pretty
2231             format (eg. "yesterday"). The format arguments are those used
2232             in the standard ``strftime`` call (see the `Python Library
2233             Reference: time module`__)
2234 popcal      Generate a link to a popup calendar which may be used to
2235             edit the date field, for example::
2237               <span tal:replace="structure context/due/popcal" />
2239             you still need to include the ``field`` for the property, so
2240             typically you'd have::
2242               <span tal:replace="structure context/due/field" />
2243               <span tal:replace="structure context/due/popcal" />
2245 menu        only on Link and Multilink properties - render a form select
2246             list for this property. Takes a number of optional arguments
2248             size
2249                is used to limit the length of the list labels
2250             height
2251                is used to set the <select> tag's "size" attribute
2252             showid
2253                includes the item ids in the list labels
2254             additional
2255                lists properties which should be included in the label
2256             sort_on
2257                 indicates the property to sort the list on as (direction,
2258                 (direction, property) where direction is '+' or '-'. A
2259                 single string with the direction prepended may be used.
2260                 For example: ('-', 'order'), '+name'.
2261             value
2262                 gives a default value to preselect in the menu
2264             The remaining keyword arguments are used as conditions for
2265             filtering the items in the list - they're passed as the
2266             "filterspec" argument to a Class.filter() call. For example::
2268              <span tal:replace="structure context/status/menu" />
2270              <span tal:replace="python:context.status.menu(order='+name",
2271                                    value='chatting', 
2272                                    filterspec={'status': '1,2,3,4'}" />
2274 sorted      only on Multilink properties - produce a list of the linked
2275             items sorted by some property, for example::
2276             
2277                 python:context.files.sorted('creation')
2279             Will list the files by upload date.
2280 reverse     only on Multilink properties - produce a list of the linked
2281             items in reverse order
2282 isset       returns True if the property has been set to a value
2283 =========== ================================================================
2285 __ http://docs.python.org/lib/module-time.html
2287 All of the above functions perform checks for permissions required to
2288 display or edit the data they are manipulating. The simplest case is
2289 editing an issue title. Including the expression::
2291    context/title/field
2293 Will present the user with an edit field, if they have edit permission. If
2294 not, then they will be presented with a static display if they have view
2295 permission. If they don't even have view permission, then an error message
2296 is raised, preventing the display of the page, indicating that they don't
2297 have permission to view the information.
2300 The request variable
2301 ~~~~~~~~~~~~~~~~~~~~
2303 This is implemented by the ``roundup.cgi.templating.HTMLRequest``
2304 class.
2306 The request variable is packed with information about the current
2307 request.
2309 .. taken from ``roundup.cgi.templating.HTMLRequest`` docstring
2311 =========== ============================================================
2312 Variable    Holds
2313 =========== ============================================================
2314 form        the CGI form as a cgi.FieldStorage
2315 env         the CGI environment variables
2316 base        the base URL for this tracker
2317 user        a HTMLUser instance for this user
2318 classname   the current classname (possibly None)
2319 template    the current template (suffix, also possibly None)
2320 form        the current CGI form variables in a FieldStorage
2321 =========== ============================================================
2323 **Index page specific variables (indexing arguments)**
2325 =========== ============================================================
2326 Variable    Holds
2327 =========== ============================================================
2328 columns     dictionary of the columns to display in an index page
2329 show        a convenience access to columns - request/show/colname will
2330             be true if the columns should be displayed, false otherwise
2331 sort        index sort columns [(direction, column name)]
2332 group       index grouping properties [(direction, column name)]
2333 filter      properties to filter the index on
2334 filterspec  values to filter the index on (property=value, eg
2335             ``priority=1`` or ``messages.author=42``
2336 search_text text to perform a full-text search on for an index
2337 =========== ============================================================
2339 There are several methods available on the request variable:
2341 =============== ========================================================
2342 Method          Description
2343 =============== ========================================================
2344 description     render a description of the request - handle for the
2345                 page title
2346 indexargs_form  render the current index args as form elements
2347 indexargs_url   render the current index args as a URL
2348 base_javascript render some javascript that is used by other components
2349                 of the templating
2350 batch           run the current index args through a filter and return a
2351                 list of items (see `hyperdb item wrapper`_, and
2352                 `batching`_)
2353 =============== ========================================================
2355 The form variable
2356 :::::::::::::::::
2358 The form variable is a bit special because it's actually a python
2359 FieldStorage object. That means that you have two ways to access its
2360 contents. For example, to look up the CGI form value for the variable
2361 "name", use the path expression::
2363    request/form/name/value
2365 or the python expression::
2367    python:request.form['name'].value
2369 Note the "item" access used in the python case, and also note the
2370 explicit "value" attribute we have to access. That's because the form
2371 variables are stored as MiniFieldStorages. If there's more than one
2372 "name" value in the form, then the above will break since
2373 ``request/form/name`` is actually a *list* of MiniFieldStorages. So it's
2374 best to know beforehand what you're dealing with.
2377 The db variable
2378 ~~~~~~~~~~~~~~~
2380 This is implemented by the ``roundup.cgi.templating.HTMLDatabase``
2381 class.
2383 Allows access to all hyperdb classes as attributes of this variable. If
2384 you want access to the "user" class, for example, you would use::
2386   db/user
2387   python:db.user
2389 Also, the current id of the current user is available as
2390 ``db.getuid()``. This isn't so useful in templates (where you have
2391 ``request/user``), but it can be useful in detectors or interfaces.
2393 The access results in a `hyperdb class wrapper`_.
2396 The templates variable
2397 ~~~~~~~~~~~~~~~~~~~~~~
2399 This is implemented by the ``roundup.cgi.templating.Templates``
2400 class.
2402 This variable doesn't have any useful methods defined. It supports being
2403 used in expressions to access the templates, and consequently the
2404 template macros. You may access the templates using the following path
2405 expression::
2407    templates/name
2409 or the python expression::
2411    templates[name]
2413 where "name" is the name of the template you wish to access. The
2414 template has one useful attribute, namely "macros". To access a specific
2415 macro (called "macro_name"), use the path expression::
2417    templates/name/macros/macro_name
2419 or the python expression::
2421    templates[name].macros[macro_name]
2423 The repeat variable
2424 ~~~~~~~~~~~~~~~~~~~
2426 The repeat variable holds an entry for each active iteration. That is, if
2427 you have a ``tal:repeat="user db/users"`` command, then there will be a
2428 repeat variable entry called "user". This may be accessed as either::
2430     repeat/user
2431     python:repeat['user']
2433 The "user" entry has a number of methods available for information:
2435 =============== =========================================================
2436 Method          Description
2437 =============== =========================================================
2438 first           True if the current item is the first in the sequence.
2439 last            True if the current item is the last in the sequence.
2440 even            True if the current item is an even item in the sequence.
2441 odd             True if the current item is an odd item in the sequence.
2442 number          Current position in the sequence, starting from 1.
2443 letter          Current position in the sequence as a letter, a through
2444                 z, then aa through zz, and so on.
2445 Letter          Same as letter(), except uppercase.
2446 roman           Current position in the sequence as lowercase roman
2447                 numerals.
2448 Roman           Same as roman(), except uppercase.
2449 =============== =========================================================
2452 The utils variable
2453 ~~~~~~~~~~~~~~~~~~
2455 This is implemented by the
2456 ``roundup.cgi.templating.TemplatingUtils`` class, but it may be extended
2457 as described below.
2459 =============== ========================================================
2460 Method          Description
2461 =============== ========================================================
2462 Batch           return a batch object using the supplied list
2463 url_quote       quote some text as safe for a URL (ie. space, %, ...)
2464 html_quote      quote some text as safe in HTML (ie. <, >, ...)
2465 html_calendar   renders an HTML calendar used by the
2466                 ``_generic.calendar.html`` template (itself invoked by
2467                 the popupCalendar DateHTMLProperty method
2468 =============== ========================================================
2470 You may add additional utility methods by writing them in your tracker
2471 ``extensions`` directory and registering them with the templating system
2472 using ``instance.registerUtil`` (see `adding a time log to your issues`_ for
2473 an example of this).
2476 Batching
2477 ::::::::
2479 Use Batch to turn a list of items, or item ids of a given class, into a
2480 series of batches. Its usage is::
2482     python:utils.Batch(sequence, size, start, end=0, orphan=0,
2483     overlap=0)
2485 or, to get the current index batch::
2487     request/batch
2489 The parameters are:
2491 ========= ==============================================================
2492 Parameter  Usage
2493 ========= ==============================================================
2494 sequence  a list of HTMLItems
2495 size      how big to make the sequence.
2496 start     where to start (0-indexed) in the sequence.
2497 end       where to end (0-indexed) in the sequence.
2498 orphan    if the next batch would contain less items than this value,
2499           then it is combined with this batch
2500 overlap   the number of items shared between adjacent batches
2501 ========= ==============================================================
2503 All of the parameters are assigned as attributes on the batch object. In
2504 addition, it has several more attributes:
2506 =============== ========================================================
2507 Attribute       Description
2508 =============== ========================================================
2509 start           indicates the start index of the batch. *Unlike
2510                 the argument, is a 1-based index (I know, lame)*
2511 first           indicates the start index of the batch *as a 0-based
2512                 index*
2513 length          the actual number of elements in the batch
2514 sequence_length the length of the original, unbatched, sequence.
2515 =============== ========================================================
2517 And several methods:
2519 =============== ========================================================
2520 Method          Description
2521 =============== ========================================================
2522 previous        returns a new Batch with the previous batch settings
2523 next            returns a new Batch with the next batch settings
2524 propchanged     detect if the named property changed on the current item
2525                 when compared to the last item
2526 =============== ========================================================
2528 An example of batching::
2530  <table class="otherinfo">
2531   <tr><th colspan="4" class="header">Existing Keywords</th></tr>
2532   <tr tal:define="keywords db/keyword/list"
2533       tal:repeat="start python:range(0, len(keywords), 4)">
2534    <td tal:define="batch python:utils.Batch(keywords, 4, start)"
2535        tal:repeat="keyword batch" tal:content="keyword/name">
2536        keyword here</td>
2537   </tr>
2538  </table>
2540 ... which will produce a table with four columns containing the items of
2541 the "keyword" class (well, their "name" anyway).
2544 Displaying Properties
2545 ---------------------
2547 Properties appear in the user interface in three contexts: in indices,
2548 in editors, and as search arguments. For each type of property, there
2549 are several display possibilities. For example, in an index view, a
2550 string property may just be printed as a plain string, but in an editor
2551 view, that property may be displayed in an editable field.
2554 Index Views
2555 -----------
2557 This is one of the class context views. It is also the default view for
2558 classes. The template used is "*classname*.index".
2561 Index View Specifiers
2562 ~~~~~~~~~~~~~~~~~~~~~
2564 An index view specifier (URL fragment) looks like this (whitespace has
2565 been added for clarity)::
2567     /issue?status=unread,in-progress,resolved&
2568         keyword=security,ui&
2569         @group=priority,-status&
2570         @sort=-activity&
2571         @filters=status,keyword&
2572         @columns=title,status,fixer
2574 The index view is determined by two parts of the specifier: the layout
2575 part and the filter part. The layout part consists of the query
2576 parameters that begin with colons, and it determines the way that the
2577 properties of selected items are displayed. The filter part consists of
2578 all the other query parameters, and it determines the criteria by which
2579 items are selected for display. The filter part is interactively
2580 manipulated with the form widgets displayed in the filter section. The
2581 layout part is interactively manipulated by clicking on the column
2582 headings in the table.
2584 The filter part selects the union of the sets of items with values
2585 matching any specified Link properties and the intersection of the sets
2586 of items with values matching any specified Multilink properties.
2588 The example specifies an index of "issue" items. Only items with a
2589 "status" of either "unread" or "in-progress" or "resolved" are
2590 displayed, and only items with "keyword" values including both "security"
2591 and "ui" are displayed. The items are grouped by priority arranged in
2592 ascending order and in descending order by status; and within
2593 groups, sorted by activity, arranged in descending order. The filter
2594 section shows filters for the "status" and "keyword" properties, and the
2595 table includes columns for the "title", "status", and "fixer"
2596 properties.
2598 ============ =============================================================
2599 Argument     Description
2600 ============ =============================================================
2601 @sort        sort by prop name, optionally preceeded with '-' to give
2602              descending or nothing for ascending sorting. Several
2603              properties can be specified delimited with comma.
2604              Internally a search-page using several sort properties may
2605              use @sort0, @sort1 etc. with option @sortdir0, @sortdir1
2606              etc. for the direction of sorting (a non-empty value of
2607              sortdir0 specifies reverse order).
2608 @group       group by prop name, optionally preceeded with '-' or to sort
2609              in descending or nothing for ascending order. Several
2610              properties can be specified delimited with comma.
2611              Internally a search-page using several grouping properties may
2612              use @group0, @group1 etc. with option @groupdir0, @groupdir1
2613              etc. for the direction of grouping (a non-empty value of
2614              groupdir0 specifies reverse order).
2615 @columns     selects the columns that should be displayed. Default is
2616              all.                     
2617 @filter      indicates which properties are being used in filtering.
2618              Default is none.
2619 propname     selects the values the item properties given by propname must
2620              have (very basic search/filter).
2621 @search_text if supplied, performs a full-text search (message bodies,
2622              issue titles, etc)
2623 ============ =============================================================
2626 Searching Views
2627 ---------------
2629 .. note::
2630    if you add a new column to the ``@columns`` form variable potentials
2631    then you will need to add the column to the appropriate `index views`_
2632    template so that it is actually displayed.
2634 This is one of the class context views. The template used is typically
2635 "*classname*.search". The form on this page should have "search" as its
2636 ``@action`` variable. The "search" action:
2638 - sets up additional filtering, as well as performing indexed text
2639   searching
2640 - sets the ``@filter`` variable correctly
2641 - saves the query off if ``@query_name`` is set.
2643 The search page should lay out any fields that you wish to allow the
2644 user to search on. If your schema contains a large number of properties,
2645 you should be wary of making all of those properties available for
2646 searching, as this can cause confusion. If the additional properties are
2647 Strings, consider having their value indexed, and then they will be
2648 searchable using the full text indexed search. This is both faster, and
2649 more useful for the end user.
2651 If the search view does specify the "search" ``@action``, then it may also
2652 provide an additional argument:
2654 ============ =============================================================
2655 Argument     Description
2656 ============ =============================================================
2657 @query_name  if supplied, the index parameters (including @search_text)
2658              will be saved off as a the query item and registered against
2659              the user's queries property. Note that the *classic* template
2660              schema has this ability, but the *minimal* template schema
2661              does not.
2662 ============ =============================================================
2665 Item Views
2666 ----------
2668 The basic view of a hyperdb item is provided by the "*classname*.item"
2669 template. It generally has three sections; an "editor", a "spool" and a
2670 "history" section.
2673 Editor Section
2674 ~~~~~~~~~~~~~~
2676 The editor section is used to manipulate the item - it may be a static
2677 display if the user doesn't have permission to edit the item.
2679 Here's an example of a basic editor template (this is the default
2680 "classic" template issue item edit form - from the "issue.item.html"
2681 template)::
2683  <table class="form">
2684  <tr>
2685   <th>Title</th>
2686   <td colspan="3" tal:content="structure python:context.title.field(size=60)">title</td>
2687  </tr>
2688  
2689  <tr>
2690   <th>Priority</th>
2691   <td tal:content="structure context/priority/menu">priority</td>
2692   <th>Status</th>
2693   <td tal:content="structure context/status/menu">status</td>
2694  </tr>
2695  
2696  <tr>
2697   <th>Superseder</th>
2698   <td>
2699    <span tal:replace="structure python:context.superseder.field(showid=1, size=20)" />
2700    <span tal:replace="structure python:db.issue.classhelp('id,title')" />
2701    <span tal:condition="context/superseder">
2702     <br>View: <span tal:replace="structure python:context.superseder.link(showid=1)" />
2703    </span>
2704   </td>
2705   <th>Nosy List</th>
2706   <td>
2707    <span tal:replace="structure context/nosy/field" />
2708    <span tal:replace="structure python:db.user.classhelp('username,realname,address,phone')" />
2709   </td>
2710  </tr>
2711  
2712  <tr>
2713   <th>Assigned To</th>
2714   <td tal:content="structure context/assignedto/menu">
2715    assignedto menu
2716   </td>
2717   <td>&nbsp;</td>
2718   <td>&nbsp;</td>
2719  </tr>
2720  
2721  <tr>
2722   <th>Change Note</th>
2723   <td colspan="3">
2724    <textarea name=":note" wrap="hard" rows="5" cols="60"></textarea>
2725   </td>
2726  </tr>
2727  
2728  <tr>
2729   <th>File</th>
2730   <td colspan="3"><input type="file" name=":file" size="40"></td>
2731  </tr>
2732  
2733  <tr>
2734   <td>&nbsp;</td>
2735   <td colspan="3" tal:content="structure context/submit">
2736    submit button will go here
2737   </td>
2738  </tr>
2739  </table>
2742 When a change is submitted, the system automatically generates a message
2743 describing the changed properties. As shown in the example, the editor
2744 template can use the ":note" and ":file" fields, which are added to the
2745 standard changenote message generated by Roundup.
2748 Form values
2749 :::::::::::
2751 We have a number of ways to pull properties out of the form in order to
2752 meet the various needs of:
2754 1. editing the current item (perhaps an issue item)
2755 2. editing information related to the current item (eg. messages or
2756    attached files)
2757 3. creating new information to be linked to the current item (eg. time
2758    spent on an issue)
2760 In the following, ``<bracketed>`` values are variable, ":" may be one of
2761 ":" or "@", and other text ("required") is fixed.
2763 Properties are specified as form variables:
2765 ``<propname>``
2766   property on the current context item
2768 ``<designator>:<propname>``
2769   property on the indicated item (for editing related information)
2771 ``<classname>-<N>:<propname>``
2772   property on the Nth new item of classname (generally for creating new
2773   items to attach to the current item)
2775 Once we have determined the "propname", we check to see if it is one of
2776 the special form values:
2778 ``@required``
2779   The named property values must be supplied or a ValueError will be
2780   raised.
2782 ``@remove@<propname>=id(s)``
2783   The ids will be removed from the multilink property.
2785 ``:add:<propname>=id(s)``
2786   The ids will be added to the multilink property.
2788 ``:link:<propname>=<designator>``
2789   Used to add a link to new items created during edit. These are
2790   collected and returned in ``all_links``. This will result in an
2791   additional linking operation (either Link set or Multilink append)
2792   after the edit/create is done using ``all_props`` in ``_editnodes``.
2793   The <propname> on the current item will be set/appended the id of the
2794   newly created item of class <designator> (where <designator> must be
2795   <classname>-<N>).
2797 Any of the form variables may be prefixed with a classname or
2798 designator.
2800 Two special form values are supported for backwards compatibility:
2802 ``:note``
2803   create a message (with content, author and date), linked to the
2804   context item. This is ALWAYS designated "msg-1".
2805 ``:file``
2806   create a file, attached to the current item and any message created by
2807   :note. This is ALWAYS designated "file-1".
2810 Spool Section
2811 ~~~~~~~~~~~~~
2813 The spool section lists related information like the messages and files
2814 of an issue.
2816 TODO
2819 History Section
2820 ~~~~~~~~~~~~~~~
2822 The final section displayed is the history of the item - its database
2823 journal. This is generally generated with the template::
2825  <tal:block tal:replace="structure context/history" />
2827 *To be done:*
2829 *The actual history entries of the item may be accessed for manual
2830 templating through the "journal" method of the item*::
2832  <tal:block tal:repeat="entry context/journal">
2833   a journal entry
2834  </tal:block>
2836 *where each journal entry is an HTMLJournalEntry.*
2839 Defining new web actions
2840 ------------------------
2842 You may define new actions to be triggered by the ``@action`` form variable.
2843 These are added to the tracker ``extensions`` directory and registered
2844 using ``instance.registerAction``.
2846 All the existing Actions are defined in ``roundup.cgi.actions``.
2848 Adding action classes takes three steps; first you `define the new
2849 action class`_, then you `register the action class`_ with the cgi
2850 interface so it may be triggered by the ``@action`` form variable.
2851 Finally you `use the new action`_ in your HTML form.
2853 See "`setting up a "wizard" (or "druid") for controlled adding of
2854 issues`_" for an example.
2857 Define the new action class
2858 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2860 Create a new action class in your tracker's ``extensions`` directory, for
2861 example ``myaction.py``::
2863  from roundup.cgi.actions import Action
2865  class MyAction(Action):
2866      def handle(self):
2867          ''' Perform some action. No return value is required.
2868          '''
2870 The *self.client* attribute is an instance of ``roundup.cgi.client.Client``.
2871 See the docstring of that class for details of what it can do.
2873 The method will typically check the ``self.form`` variable's contents.
2874 It may then:
2876 - add information to ``self.client.ok_message`` or ``self.client.error_message``
2877 - change the ``self.client.template`` variable to alter what the user will see
2878   next
2879 - raise Unauthorised, SendStaticFile, SendFile, NotFound or Redirect
2880   exceptions (import them from roundup.cgi.exceptions)
2883 Register the action class
2884 ~~~~~~~~~~~~~~~~~~~~~~~~~~
2886 The class is now written, but isn't available to the user until you register
2887 it with the following code appended to your ``myaction.py`` file::
2889     def init(instance):
2890         instance.registerAction('myaction', myActionClass)
2892 This maps the action name "myaction" to the action class we defined.
2895 Use the new action
2896 ~~~~~~~~~~~~~~~~~~
2898 In your HTML form, add a hidden form element like so::
2900   <input type="hidden" name="@action" value="myaction">
2902 where "myaction" is the name you registered in the previous step.
2904 Actions may return content to the user
2905 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2907 Actions generally perform some database manipulation and then pass control
2908 on to the rendering of a template in the current context (see `Determining
2909 web context`_ for how that works.) Some actions will want to generate the
2910 actual content returned to the user. Action methods may return their own
2911 content string to be displayed to the user, overriding the templating step.
2912 In this situation, we assume that the content is HTML by default. You may
2913 override the content type indicated to the user by calling ``setHeader``::
2915    self.client.setHeader('Content-Type', 'text/csv')
2917 This example indicates that the value sent back to the user is actually
2918 comma-separated value content (eg. something to be loaded into a
2919 spreadsheet or database).
2922 8-bit character set support in Web interface
2923 --------------------------------------------
2925 The web interface uses UTF-8 default. It may be overridden in both forms
2926 and a browser cookie.
2928 - In forms, use the ``@charset`` variable.
2929 - To use the cookie override, have the ``roundup_charset`` cookie set.
2931 In both cases, the value is a valid charset name (eg. ``utf-8`` or
2932 ``kio8-r``).
2934 Inside Roundup, all strings are stored and processed in utf-8.
2935 Unfortunately, some older browsers do not work properly with
2936 utf-8-encoded pages (e.g. Netscape Navigator 4 displays wrong
2937 characters in form fields).  This version allows one to change
2938 the character set for http transfers.  To do so, you may add
2939 the following code to your ``page.html`` template::
2941  <tal:block define="uri string:${request/base}${request/env/PATH_INFO}">
2942   <a tal:attributes="href python:request.indexargs_url(uri,
2943    {'@charset':'utf-8'})">utf-8</a>
2944   <a tal:attributes="href python:request.indexargs_url(uri,
2945    {'@charset':'koi8-r'})">koi8-r</a>
2946  </tal:block>
2948 (substitute ``koi8-r`` with appropriate charset for your language).
2949 Charset preference is kept in the browser cookie ``roundup_charset``.
2951 ``meta http-equiv`` lines added to the tracker templates in version 0.6.0
2952 should be changed to include actual character set name::
2954  <meta http-equiv="Content-Type"
2955   tal:attributes="content string:text/html;; charset=${request/client/charset}"
2956  />
2958 The charset is also sent in the http header.
2961 Examples
2962 ========
2964 .. contents::
2965    :local:
2966    :depth: 2
2969 Changing what's stored in the database
2970 --------------------------------------
2972 The following examples illustrate ways to change the information stored in
2973 the database.
2976 Adding a new field to the classic schema
2977 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2979 This example shows how to add a simple field (a due date) to the default
2980 classic schema. It does not add any additional behaviour, such as enforcing
2981 the due date, or causing automatic actions to fire if the due date passes.
2983 You add new fields by editing the ``schema.py`` file in you tracker's home.
2984 Schema changes are automatically applied to the database on the next
2985 tracker access (note that roundup-server would need to be restarted as it
2986 caches the schema).
2988 1. Modify the ``schema.py``::
2990     issue = IssueClass(db, "issue", 
2991                     assignedto=Link("user"), keyword=Multilink("keyword"),
2992                     priority=Link("priority"), status=Link("status"),
2993                     due_date=Date())
2995 2. Add an edit field to the ``issue.item.html`` template::
2997     <tr> 
2998      <th>Due Date</th> 
2999      <td tal:content="structure context/due_date/field" /> 
3000     </tr>
3001     
3002    If you want to show only the date part of due_date then do this instead::
3003    
3004     <tr> 
3005      <th>Due Date</th> 
3006      <td tal:content="structure python:context.due_date.field(format='%Y-%m-%d')" /> 
3007     </tr>
3009 3. Add the property to the ``issue.index.html`` page::
3011     (in the heading row)
3012       <th tal:condition="request/show/due_date">Due Date</th>
3013     (in the data row)
3014       <td tal:condition="request/show/due_date" 
3015           tal:content="i/due_date" />
3016           
3017    If you want format control of the display of the due date you can
3018    enter the following in the data row to show only the actual due date::
3019     
3020       <td tal:condition="request/show/due_date" 
3021           tal:content="python:i.due_date.pretty('%Y-%m-%d')">&nbsp;</td>
3023 4. Add the property to the ``issue.search.html`` page::
3025      <tr tal:define="name string:due_date">
3026        <th i18n:translate="">Due Date:</th>
3027        <td metal:use-macro="search_input"></td>
3028        <td metal:use-macro="column_input"></td>
3029        <td metal:use-macro="sort_input"></td>
3030        <td metal:use-macro="group_input"></td>
3031      </tr>
3033 5. If you wish for the due date to appear in the standard views listed
3034    in the sidebar of the web interface then you'll need to add "due_date"
3035    to the columns and columns_showall lists in your ``page.html``::
3036     
3037     columns string:id,activity,due_date,title,creator,status;
3038     columns_showall string:id,activity,due_date,title,creator,assignedto,status;
3040 Adding a new constrained field to the classic schema
3041 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3043 This example shows how to add a new constrained property (i.e. a
3044 selection of distinct values) to your tracker.
3047 Introduction
3048 ::::::::::::
3050 To make the classic schema of Roundup useful as a TODO tracking system
3051 for a group of systems administrators, it needs an extra data field per
3052 issue: a category.
3054 This would let sysadmins quickly list all TODOs in their particular area
3055 of interest without having to do complex queries, and without relying on
3056 the spelling capabilities of other sysadmins (a losing proposition at
3057 best).
3060 Adding a field to the database
3061 ::::::::::::::::::::::::::::::
3063 This is the easiest part of the change. The category would just be a
3064 plain string, nothing fancy. To change what is in the database you need
3065 to add some lines to the ``schema.py`` file of your tracker instance.
3066 Under the comment::
3068     # add any additional database schema configuration here
3070 add::
3072     category = Class(db, "category", name=String())
3073     category.setkey("name")
3075 Here we are setting up a chunk of the database which we are calling
3076 "category". It contains a string, which we are refering to as "name" for
3077 lack of a more imaginative title. (Since "name" is one of the properties
3078 that Roundup looks for on items if you do not set a key for them, it's
3079 probably a good idea to stick with it for new classes if at all
3080 appropriate.) Then we are setting the key of this chunk of the database
3081 to be that "name". This is equivalent to an index for database types.
3082 This also means that there can only be one category with a given name.
3084 Adding the above lines allows us to create categories, but they're not
3085 tied to the issues that we are going to be creating. It's just a list of
3086 categories off on its own, which isn't much use. We need to link it in
3087 with the issues. To do that, find the lines 
3088 in ``schema.py`` which set up the "issue" class, and then add a link to
3089 the category::
3091     issue = IssueClass(db, "issue", ... ,
3092         category=Multilink("category"), ... )
3094 The ``Multilink()`` means that each issue can have many categories. If
3095 you were adding something with a one-to-one relationship to issues (such
3096 as the "assignedto" property), use ``Link()`` instead.
3098 That is all you need to do to change the schema. The rest of the effort
3099 is fiddling around so you can actually use the new category.
3102 Populating the new category class
3103 :::::::::::::::::::::::::::::::::
3105 If you haven't initialised the database with the ``roundup-admin``
3106 "initialise" command, then you can add the following to the tracker
3107 ``initial_data.py`` under the comment::
3109     # add any additional database creation steps here - but only if you
3110     # haven't initialised the database with the admin "initialise" command
3112 Add::
3114      category = db.getclass('category')
3115      category.create(name="scipy")
3116      category.create(name="chaco")
3117      category.create(name="weave")
3119 If the database has already been initalised, then you need to use the
3120 ``roundup-admin`` tool::
3122      % roundup-admin -i <tracker home>
3123      Roundup <version> ready for input.
3124      Type "help" for help.
3125      roundup> create category name=scipy
3126      1
3127      roundup> create category name=chaco
3128      2
3129      roundup> create category name=weave
3130      3
3131      roundup> exit...
3132      There are unsaved changes. Commit them (y/N)? y
3135 Setting up security on the new objects
3136 ::::::::::::::::::::::::::::::::::::::
3138 By default only the admin user can look at and change objects. This
3139 doesn't suit us, as we want any user to be able to create new categories
3140 as required, and obviously everyone needs to be able to view the
3141 categories of issues for it to be useful.
3143 We therefore need to change the security of the category objects. This
3144 is also done in ``schema.py``.
3146 There are currently two loops which set up permissions and then assign
3147 them to various roles. Simply add the new "category" to both lists::
3149     # Assign the access and edit permissions for issue, file and message
3150     # to regular users now
3151     for cl in 'issue', 'file', 'msg', 'category':
3152         p = db.security.getPermission('View', cl)
3153         db.security.addPermissionToRole('User', 'View', cl)
3154         db.security.addPermissionToRole('User', 'Edit', cl)
3155         db.security.addPermissionToRole('User', 'Create', cl)
3157 These lines assign the "View" and "Edit" Permissions to the "User" role,
3158 so that normal users can view and edit "category" objects.
3160 This is all the work that needs to be done for the database. It will
3161 store categories, and let users view and edit them. Now on to the
3162 interface stuff.
3165 Changing the web left hand frame
3166 ::::::::::::::::::::::::::::::::
3168 We need to give the users the ability to create new categories, and the
3169 place to put the link to this functionality is in the left hand function
3170 bar, under the "Issues" area. The file that defines how this area looks
3171 is ``html/page.html``, which is what we are going to be editing next.
3173 If you look at this file you can see that it contains a lot of
3174 "classblock" sections which are chunks of HTML that will be included or
3175 excluded in the output depending on whether the condition in the
3176 classblock is met. We are going to add the category code at the end of
3177 the classblock for the *issue* class::
3179   <p class="classblock"
3180      tal:condition="python:request.user.hasPermission('View', 'category')">
3181    <b>Categories</b><br>
3182    <a tal:condition="python:request.user.hasPermission('Edit', 'category')"
3183       href="category?@template=item">New Category<br></a>
3184   </p>
3186 The first two lines is the classblock definition, which sets up a
3187 condition that only users who have "View" permission for the "category"
3188 object will have this section included in their output. Next comes a
3189 plain "Categories" header in bold. Everyone who can view categories will
3190 get that.
3192 Next comes the link to the editing area of categories. This link will
3193 only appear if the condition - that the user has "Edit" permissions for
3194 the "category" objects - is matched. If they do have permission then
3195 they will get a link to another page which will let the user add new
3196 categories.
3198 Note that if you have permission to *view* but not to *edit* categories,
3199 then all you will see is a "Categories" header with nothing underneath
3200 it. This is obviously not very good interface design, but will do for
3201 now. I just claim that it is so I can add more links in this section
3202 later on. However, to fix the problem you could change the condition in
3203 the classblock statement, so that only users with "Edit" permission
3204 would see the "Categories" stuff.
3207 Setting up a page to edit categories
3208 ::::::::::::::::::::::::::::::::::::
3210 We defined code in the previous section which let users with the
3211 appropriate permissions see a link to a page which would let them edit
3212 conditions. Now we have to write that page.
3214 The link was for the *item* template of the *category* object. This
3215 translates into Roundup looking for a file called ``category.item.html``
3216 in the ``html`` tracker directory. This is the file that we are going to
3217 write now.
3219 First, we add an info tag in a comment which doesn't affect the outcome
3220 of the code at all, but is useful for debugging. If you load a page in a
3221 browser and look at the page source, you can see which sections come
3222 from which files by looking for these comments::
3224     <!-- category.item -->
3226 Next we need to add in the METAL macro stuff so we get the normal page
3227 trappings::
3229  <tal:block metal:use-macro="templates/page/macros/icing">
3230   <title metal:fill-slot="head_title">Category editing</title>
3231   <td class="page-header-top" metal:fill-slot="body_title">
3232    <h2>Category editing</h2>
3233   </td>
3234   <td class="content" metal:fill-slot="content">
3236 Next we need to setup up a standard HTML form, which is the whole
3237 purpose of this file. We link to some handy javascript which sends the
3238 form through only once. This is to stop users hitting the send button
3239 multiple times when they are impatient and thus having the form sent
3240 multiple times::
3242     <form method="POST" onSubmit="return submit_once()"
3243           enctype="multipart/form-data">
3245 Next we define some code which sets up the minimum list of fields that
3246 we require the user to enter. There will be only one field - "name" - so
3247 they better put something in it, otherwise the whole form is pointless::
3249     <input type="hidden" name="@required" value="name">
3251 To get everything to line up properly we will put everything in a table,
3252 and put a nice big header on it so the user has an idea what is
3253 happening::
3255     <table class="form">
3256      <tr><th class="header" colspan="2">Category</th></tr>
3258 Next, we need the field into which the user is going to enter the new
3259 category. The ``context.name.field(size=60)`` bit tells Roundup to
3260 generate a normal HTML field of size 60, and the contents of that field
3261 will be the "name" variable of the current context (namely "category").
3262 The upshot of this is that when the user types something in
3263 to the form, a new category will be created with that name::
3265     <tr>
3266      <th>Name</th>
3267      <td tal:content="structure python:context.name.field(size=60)">
3268      name</td>
3269     </tr>
3271 Then a submit button so that the user can submit the new category::
3273     <tr>
3274      <td>&nbsp;</td>
3275      <td colspan="3" tal:content="structure context/submit">
3276       submit button will go here
3277      </td>
3278     </tr>
3280 Finally we finish off the tags we used at the start to do the METAL
3281 stuff::
3283   </td>
3284  </tal:block>
3286 So putting it all together, and closing the table and form we get::
3288  <!-- category.item -->
3289  <tal:block metal:use-macro="templates/page/macros/icing">
3290   <title metal:fill-slot="head_title">Category editing</title>
3291   <td class="page-header-top" metal:fill-slot="body_title">
3292    <h2>Category editing</h2>
3293   </td>
3294   <td class="content" metal:fill-slot="content">
3295    <form method="POST" onSubmit="return submit_once()"
3296          enctype="multipart/form-data">
3298     <table class="form">
3299      <tr><th class="header" colspan="2">Category</th></tr>
3301      <tr>
3302       <th>Name</th>
3303       <td tal:content="structure python:context.name.field(size=60)">
3304       name</td>
3305      </tr>
3307      <tr>
3308       <td>
3309         &nbsp;
3310         <input type="hidden" name="@required" value="name"> 
3311       </td>
3312       <td colspan="3" tal:content="structure context/submit">
3313        submit button will go here
3314       </td>
3315      </tr>
3316     </table>
3317    </form>
3318   </td>
3319  </tal:block>
3321 This is quite a lot to just ask the user one simple question, but there
3322 is a lot of setup for basically one line (the form line) to do its work.
3323 To add another field to "category" would involve one more line (well,
3324 maybe a few extra to get the formatting correct).
3327 Adding the category to the issue
3328 ::::::::::::::::::::::::::::::::
3330 We now have the ability to create issues to our heart's content, but
3331 that is pointless unless we can assign categories to issues.  Just like
3332 the ``html/category.item.html`` file was used to define how to add a new
3333 category, the ``html/issue.item.html`` is used to define how a new issue
3334 is created.
3336 Just like ``category.issue.html``, this file defines a form which has a
3337 table to lay things out. It doesn't matter where in the table we add new
3338 stuff, it is entirely up to your sense of aesthetics::
3340    <th>Category</th>
3341    <td>
3342     <span tal:replace="structure context/category/field" />
3343     <span tal:replace="structure python:db.category.classhelp('name',
3344                 property='category', width='200')" />
3345    </td>
3347 First, we define a nice header so that the user knows what the next
3348 section is, then the middle line does what we are most interested in.
3349 This ``context/category/field`` gets replaced by a field which contains
3350 the category in the current context (the current context being the new
3351 issue).
3353 The classhelp lines generate a link (labelled "list") to a popup window
3354 which contains the list of currently known categories.
3357 Searching on categories
3358 :::::::::::::::::::::::
3360 Now we can add categories, and create issues with categories. The next
3361 obvious thing that we would like to be able to do, would be to search
3362 for issues based on their category, so that, for example, anyone working
3363 on the web server could look at all issues in the category "Web".
3365 If you look for "Search Issues" in the ``html/page.html`` file, you will
3366 find that it looks something like 
3367 ``<a href="issue?@template=search">Search Issues</a>``. This shows us
3368 that when you click on "Search Issues" it will be looking for a
3369 ``issue.search.html`` file to display. So that is the file that we will
3370 change.
3372 If you look at this file it should begin to seem familiar, although it
3373 does use some new macros. You can add the new category search code anywhere you
3374 like within that form::
3376   <tr tal:define="name string:category;
3377                   db_klass string:category;
3378                   db_content string:name;">
3379     <th>Priority:</th>
3380     <td metal:use-macro="search_select"></td>
3381     <td metal:use-macro="column_input"></td>
3382     <td metal:use-macro="sort_input"></td>
3383     <td metal:use-macro="group_input"></td>
3384   </tr>
3386 The definitions in the ``<tr>`` opening tag are used by the macros:
3388 - ``search_select`` expands to a drop-down box with all categories using
3389   ``db_klass`` and ``db_content``.
3390 - ``column_input`` expands to a checkbox for selecting what columns
3391   should be displayed.
3392 - ``sort_input`` expands to a radio button for selecting what property
3393   should be sorted on.
3394 - ``group_input`` expands to a radio button for selecting what property
3395   should be grouped on.
3397 The category search code above would expand to the following::
3399   <tr>
3400     <th>Category:</th>
3401     <td>
3402       <select name="category">
3403         <option value="">don't care</option>
3404         <option value="">------------</option>      
3405         <option value="1">scipy</option>
3406         <option value="2">chaco</option>
3407         <option value="3">weave</option>
3408       </select>
3409     </td>
3410     <td><input type="checkbox" name=":columns" value="category"></td>
3411     <td><input type="radio" name=":sort0" value="category"></td>
3412     <td><input type="radio" name=":group0" value="category"></td>
3413   </tr>
3415 Adding category to the default view
3416 :::::::::::::::::::::::::::::::::::
3418 We can now add categories, add issues with categories, and search for
3419 issues based on categories. This is everything that we need to do;
3420 however, there is some more icing that we would like. I think the
3421 category of an issue is important enough that it should be displayed by
3422 default when listing all the issues.
3424 Unfortunately, this is a bit less obvious than the previous steps. The
3425 code defining how the issues look is in ``html/issue.index.html``. This
3426 is a large table with a form down at the bottom for redisplaying and so
3427 forth. 
3429 Firstly we need to add an appropriate header to the start of the table::
3431     <th tal:condition="request/show/category">Category</th>
3433 The *condition* part of this statement is to avoid displaying the
3434 Category column if the user has selected not to see it.
3436 The rest of the table is a loop which will go through every issue that
3437 matches the display criteria. The loop variable is "i" - which means
3438 that every issue gets assigned to "i" in turn.
3440 The new part of code to display the category will look like this::
3442     <td tal:condition="request/show/category"
3443         tal:content="i/category"></td>
3445 The condition is the same as above: only display the condition when the
3446 user hasn't asked for it to be hidden. The next part is to set the
3447 content of the cell to be the category part of "i" - the current issue.
3449 Finally we have to edit ``html/page.html`` again. This time, we need to
3450 tell it that when the user clicks on "Unassigned Issues" or "All Issues",
3451 the category column should be included in the resulting list. If you
3452 scroll down the page file, you can see the links with lots of options.
3453 The option that we are interested in is the ``:columns=`` one which
3454 tells roundup which fields of the issue to display. Simply add
3455 "category" to that list and it all should work.
3457 Adding a time log to your issues
3458 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3460 We want to log the dates and amount of time spent working on issues, and
3461 be able to give a summary of the total time spent on a particular issue.
3463 1. Add a new class to your tracker ``schema.py``::
3465     # storage for time logging
3466     timelog = Class(db, "timelog", period=Interval())
3468    Note that we automatically get the date of the time log entry
3469    creation through the standard property "creation".
3471    You will need to grant "Creation" permission to the users who are
3472    allowed to add timelog entries. You may do this with::
3474     db.security.addPermissionToRole('User', 'Create', 'timelog')
3475     db.security.addPermissionToRole('User', 'View', 'timelog')
3477    If users are also able to *edit* timelog entries, then also include::
3479     db.security.addPermissionToRole('User', 'Edit', 'timelog')
3481 2. Link to the new class from your issue class (again, in
3482    ``schema.py``)::
3484     issue = IssueClass(db, "issue", 
3485                     assignedto=Link("user"), keyword=Multilink("keyword"),
3486                     priority=Link("priority"), status=Link("status"),
3487                     times=Multilink("timelog"))
3489    the "times" property is the new link to the "timelog" class.
3491 3. We'll need to let people add in times to the issue, so in the web
3492    interface we'll have a new entry field. This is a special field
3493    because unlike the other fields in the ``issue.item`` template, it
3494    affects a different item (a timelog item) and not the template's
3495    item (an issue). We have a special syntax for form fields that affect
3496    items other than the template default item (see the cgi 
3497    documentation on `special form variables`_). In particular, we add a
3498    field to capture a new timelog item's period::
3500     <tr> 
3501      <th>Time Log</th> 
3502      <td colspan=3><input type="text" name="timelog-1@period" /> 
3503       (enter as '3y 1m 4d 2:40:02' or parts thereof) 
3504      </td> 
3505     </tr> 
3506          
3507    and another hidden field that links that new timelog item (new
3508    because it's marked as having id "-1") to the issue item. It looks
3509    like this::
3511      <input type="hidden" name="@link@times" value="timelog-1" />
3513    On submission, the "-1" timelog item will be created and assigned a
3514    real item id. The "times" property of the issue will have the new id
3515    added to it.
3516    
3517    The full entry will now look like this::
3518    
3519     <tr> 
3520      <th>Time Log</th> 
3521      <td colspan=3><input type="text" name="timelog-1@period" /> 
3522       (enter as '3y 1m 4d 2:40:02' or parts thereof)
3523       <input type="hidden" name="@link@times" value="timelog-1" /> 
3524      </td> 
3525     </tr> 
3526    
3528 4. We want to display a total of the timelog times that have been
3529    accumulated for an issue. To do this, we'll need to actually write
3530    some Python code, since it's beyond the scope of PageTemplates to
3531    perform such calculations. We do this by adding a module ``timespent.py``
3532    to the ``extensions`` directory in our tracker. The contents of this
3533    file is as follows::
3535     from roundup import date
3537     def totalTimeSpent(times):
3538         ''' Call me with a list of timelog items (which have an
3539             Interval "period" property)
3540         '''
3541         total = date.Interval('0d')
3542         for time in times:
3543             total += time.period._value
3544         return total
3546     def init(instance):
3547         instance.registerUtil('totalTimeSpent', totalTimeSpent)
3549    We will now be able to access the ``totalTimeSpent`` function via the
3550    ``utils`` variable in our templates, as shown in the next step.
3552 5. Display the timelog for an issue::
3554      <table class="otherinfo" tal:condition="context/times">
3555       <tr><th colspan="3" class="header">Time Log
3556        <tal:block
3557             tal:replace="python:utils.totalTimeSpent(context.times)" />
3558       </th></tr>
3559       <tr><th>Date</th><th>Period</th><th>Logged By</th></tr>
3560       <tr tal:repeat="time context/times">
3561        <td tal:content="time/creation"></td>
3562        <td tal:content="time/period"></td>
3563        <td tal:content="time/creator"></td>
3564       </tr>
3565      </table>
3567    I put this just above the Messages log in my issue display. Note our
3568    use of the ``totalTimeSpent`` method which will total up the times
3569    for the issue and return a new Interval. That will be automatically
3570    displayed in the template as text like "+ 1y 2:40" (1 year, 2 hours
3571    and 40 minutes).
3573 6. If you're using a persistent web server - ``roundup-server`` or
3574    ``mod_python`` for example - then you'll need to restart that to pick up
3575    the code changes. When that's done, you'll be able to use the new
3576    time logging interface.
3578 An extension of this modification attaches the timelog entries to any
3579 change message entered at the time of the timelog entry:
3581 A. Add a link to the timelog to the msg class in ``schema.py``:
3583     msg = FileClass(db, "msg",
3584                     author=Link("user", do_journal='no'),
3585                     recipients=Multilink("user", do_journal='no'),
3586                     date=Date(),
3587                     summary=String(),
3588                     files=Multilink("file"),
3589                     messageid=String(),
3590                     inreplyto=String(),
3591                     times=Multilink("timelog"))
3593 B. Add a new hidden field that links that new timelog item (new
3594    because it's marked as having id "-1") to the new message.
3595    The link is placed in ``issue.item.html`` in the same section that
3596    handles the timelog entry.
3597    
3598    It looks like this after this addition::
3600     <tr> 
3601      <th>Time Log</th> 
3602      <td colspan=3><input type="text" name="timelog-1@period" /> 
3603       (enter as '3y 1m 4d 2:40:02' or parts thereof)
3604       <input type="hidden" name="@link@times" value="timelog-1" />
3605       <input type="hidden" name="msg-1@link@times" value="timelog-1" /> 
3606      </td> 
3607     </tr> 
3608  
3609    The "times" property of the message will have the new id added to it.
3611 C. Add the timelog listing from step 5. to the ``msg.item.html`` template
3612    so that the timelog entry appears on the message view page. Note that
3613    the call to totalTimeSpent is not used here since there will only be one
3614    single timelog entry for each message.
3615    
3616    I placed it after the Date entry like this::
3617    
3618     <tr>
3619      <th i18n:translate="">Date:</th>
3620      <td tal:content="context/date"></td>
3621     </tr>
3622     </table>
3623     
3624     <table class="otherinfo" tal:condition="context/times">
3625      <tr><th colspan="3" class="header">Time Log</th></tr>
3626      <tr><th>Date</th><th>Period</th><th>Logged By</th></tr>
3627      <tr tal:repeat="time context/times">
3628       <td tal:content="time/creation"></td>
3629       <td tal:content="time/period"></td>
3630       <td tal:content="time/creator"></td>
3631      </tr>
3632     </table>
3633     
3634     <table class="messages">
3637 Tracking different types of issues
3638 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3640 Sometimes you will want to track different types of issues - developer,
3641 customer support, systems, sales leads, etc. A single Roundup tracker is
3642 able to support multiple types of issues. This example demonstrates adding
3643 a system support issue class to a tracker.
3645 1. Figure out what information you're going to want to capture. OK, so
3646    this is obvious, but sometimes it's better to actually sit down for a
3647    while and think about the schema you're going to implement.
3649 2. Add the new issue class to your tracker's ``schema.py``. Just after the
3650    "issue" class definition, add::
3652     # list our systems
3653     system = Class(db, "system", name=String(), order=Number())
3654     system.setkey("name")
3656     # store issues related to those systems
3657     support = IssueClass(db, "support", 
3658                     assignedto=Link("user"), keyword=Multilink("keyword"),
3659                     status=Link("status"), deadline=Date(),
3660                     affects=Multilink("system"))
3662 3. Copy the existing ``issue.*`` (item, search and index) templates in the
3663    tracker's ``html`` to ``support.*``. Edit them so they use the properties
3664    defined in the ``support`` class. Be sure to check for hidden form
3665    variables like "required" to make sure they have the correct set of
3666    required properties.
3668 4. Edit the modules in the ``detectors``, adding lines to their ``init``
3669    functions where appropriate. Look for ``audit`` and ``react`` registrations
3670    on the ``issue`` class, and duplicate them for ``support``.
3672 5. Create a new sidebar box for the new support class. Duplicate the
3673    existing issues one, changing the ``issue`` class name to ``support``.
3675 6. Re-start your tracker and start using the new ``support`` class.
3678 Optionally, you might want to restrict the users able to access this new
3679 class to just the users with a new "SysAdmin" Role. To do this, we add
3680 some security declarations::
3682     db.security.addPermissionToRole('SysAdmin', 'View', 'support')
3683     db.security.addPermissionToRole('SysAdmin', 'Create', 'support')
3684     db.security.addPermissionToRole('SysAdmin', 'Edit', 'support')
3686 You would then (as an "admin" user) edit the details of the appropriate
3687 users, and add "SysAdmin" to their Roles list.
3689 Alternatively, you might want to change the Edit/View permissions granted
3690 for the ``issue`` class so that it's only available to users with the "System"
3691 or "Developer" Role, and then the new class you're adding is available to
3692 all with the "User" Role.
3695 Using External User Databases
3696 -----------------------------
3698 Using an external password validation source
3699 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3701 .. note:: You will need to either have an "admin" user in your external
3702           password source *or* have one of your regular users have
3703           the Admin Role assigned. If you need to assign the Role *after*
3704           making the changes below, you may use the ``roundup-admin``
3705           program to edit a user's details.
3707 We have a centrally-managed password changing system for our users. This
3708 results in a UN*X passwd-style file that we use for verification of
3709 users. Entries in the file consist of ``name:password`` where the
3710 password is encrypted using the standard UN*X ``crypt()`` function (see
3711 the ``crypt`` module in your Python distribution). An example entry
3712 would be::
3714     admin:aamrgyQfDFSHw
3716 Each user of Roundup must still have their information stored in the Roundup
3717 database - we just use the passwd file to check their password. To do this, we
3718 need to override the standard ``verifyPassword`` method defined in
3719 ``roundup.cgi.actions.LoginAction`` and register the new class. The
3720 following is added as ``externalpassword.py`` in the tracker ``extensions``
3721 directory::
3723     import os, crypt
3724     from roundup.cgi.actions import LoginAction    
3726     class ExternalPasswordLoginAction(LoginAction):
3727         def verifyPassword(self, userid, password):
3728             '''Look through the file, line by line, looking for a
3729             name that matches.
3730             '''
3731             # get the user's username
3732             username = self.db.user.get(userid, 'username')
3734             # the passwords are stored in the "passwd.txt" file in the
3735             # tracker home
3736             file = os.path.join(self.db.config.TRACKER_HOME, 'passwd.txt')
3738             # see if we can find a match
3739             for ent in [line.strip().split(':') for line in
3740                                                 open(file).readlines()]:
3741                 if ent[0] == username:
3742                     return crypt.crypt(password, ent[1][:2]) == ent[1]
3744             # user doesn't exist in the file
3745             return 0
3747     def init(instance):
3748         instance.registerAction('login', ExternalPasswordLoginAction)
3750 You should also remove the redundant password fields from the ``user.item``
3751 template.
3754 Using a UN*X passwd file as the user database
3755 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3757 On some systems the primary store of users is the UN*X passwd file. It
3758 holds information on users such as their username, real name, password
3759 and primary user group.
3761 Roundup can use this store as its primary source of user information,
3762 but it needs additional information too - email address(es), roundup
3763 Roles, vacation flags, roundup hyperdb item ids, etc. Also, "retired"
3764 users must still exist in the user database, unlike some passwd files in
3765 which the users are removed when they no longer have access to a system.
3767 To make use of the passwd file, we therefore synchronise between the two
3768 user stores. We also use the passwd file to validate the user logins, as
3769 described in the previous example, `using an external password
3770 validation source`_. We keep the user lists in sync using a fairly
3771 simple script that runs once a day, or several times an hour if more
3772 immediate access is needed. In short, it:
3774 1. parses the passwd file, finding usernames, passwords and real names,
3775 2. compares that list to the current roundup user list:
3777    a. entries no longer in the passwd file are *retired*
3778    b. entries with mismatching real names are *updated*
3779    c. entries only exist in the passwd file are *created*
3781 3. send an email to administrators to let them know what's been done.
3783 The retiring and updating are simple operations, requiring only a call
3784 to ``retire()`` or ``set()``. The creation operation requires more
3785 information though - the user's email address and their Roundup Roles.
3786 We're going to assume that the user's email address is the same as their
3787 login name, so we just append the domain name to that. The Roles are
3788 determined using the passwd group identifier - mapping their UN*X group
3789 to an appropriate set of Roles.
3791 The script to perform all this, broken up into its main components, is
3792 as follows. Firstly, we import the necessary modules and open the
3793 tracker we're to work on::
3795     import sys, os, smtplib
3796     from roundup import instance, date
3798     # open the tracker
3799     tracker_home = sys.argv[1]
3800     tracker = instance.open(tracker_home)
3802 Next we read in the *passwd* file from the tracker home::
3804     # read in the users from the "passwd.txt" file
3805     file = os.path.join(tracker_home, 'passwd.txt')
3806     users = [x.strip().split(':') for x in open(file).readlines()]
3808 Handle special users (those to ignore in the file, and those who don't
3809 appear in the file)::
3811     # users to not keep ever, pre-load with the users I know aren't
3812     # "real" users
3813     ignore = ['ekmmon', 'bfast', 'csrmail']
3815     # users to keep - pre-load with the roundup-specific users
3816     keep = ['comment_pool', 'network_pool', 'admin', 'dev-team',
3817             'cs_pool', 'anonymous', 'system_pool', 'automated']
3819 Now we map the UN*X group numbers to the Roles that users should have::
3821     roles = {
3822      '501': 'User,Tech',  # tech
3823      '502': 'User',       # finance
3824      '503': 'User,CSR',   # customer service reps
3825      '504': 'User',       # sales
3826      '505': 'User',       # marketing
3827     }
3829 Now we do all the work. Note that the body of the script (where we have
3830 the tracker database open) is wrapped in a ``try`` / ``finally`` clause,
3831 so that we always close the database cleanly when we're finished. So, we
3832 now do all the work::
3834     # open the database
3835     db = tracker.open('admin')
3836     try:
3837         # store away messages to send to the tracker admins
3838         msg = []
3840         # loop over the users list read in from the passwd file
3841         for user,passw,uid,gid,real,home,shell in users:
3842             if user in ignore:
3843                 # this user shouldn't appear in our tracker
3844                 continue
3845             keep.append(user)
3846             try:
3847                 # see if the user exists in the tracker
3848                 uid = db.user.lookup(user)
3850                 # yes, they do - now check the real name for correctness
3851                 if real != db.user.get(uid, 'realname'):
3852                     db.user.set(uid, realname=real)
3853                     msg.append('FIX %s - %s'%(user, real))
3854             except KeyError:
3855                 # nope, the user doesn't exist
3856                 db.user.create(username=user, realname=real,
3857                     address='%s@ekit-inc.com'%user, roles=roles[gid])
3858                 msg.append('ADD %s - %s (%s)'%(user, real, roles[gid]))
3860         # now check that all the users in the tracker are also in our
3861         # "keep" list - retire those who aren't
3862         for uid in db.user.list():
3863             user = db.user.get(uid, 'username')
3864             if user not in keep:
3865                 db.user.retire(uid)
3866                 msg.append('RET %s'%user)
3868         # if we did work, then send email to the tracker admins
3869         if msg:
3870             # create the email
3871             msg = '''Subject: %s user database maintenance
3873             %s
3874             '''%(db.config.TRACKER_NAME, '\n'.join(msg))
3876             # send the email
3877             smtp = smtplib.SMTP(db.config.MAILHOST)
3878             addr = db.config.ADMIN_EMAIL
3879             smtp.sendmail(addr, addr, msg)
3881         # now we're done - commit the changes
3882         db.commit()
3883     finally:
3884         # always close the database cleanly
3885         db.close()
3887 And that's it!
3890 Using an LDAP database for user information
3891 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3893 A script that reads users from an LDAP store using
3894 http://python-ldap.sf.net/ and then compares the list to the users in the
3895 roundup user database would be pretty easy to write. You'd then have it run
3896 once an hour / day (or on demand if you can work that into your LDAP store
3897 workflow). See the example `Using a UN*X passwd file as the user database`_
3898 for more information about doing this.
3900 To authenticate off the LDAP store (rather than using the passwords in the
3901 Roundup user database) you'd use the same python-ldap module inside an
3902 extension to the cgi interface. You'd do this by overriding the method called
3903 ``verifyPassword`` on the ``LoginAction`` class in your tracker's
3904 ``extensions`` directory (see `using an external password validation
3905 source`_). The method is implemented by default as::
3907     def verifyPassword(self, userid, password):
3908         ''' Verify the password that the user has supplied
3909         '''
3910         stored = self.db.user.get(self.userid, 'password')
3911         if password == stored:
3912             return 1
3913         if not password and not stored:
3914             return 1
3915         return 0
3917 So you could reimplement this as something like::
3919     def verifyPassword(self, userid, password):
3920         ''' Verify the password that the user has supplied
3921         '''
3922         # look up some unique LDAP information about the user
3923         username = self.db.user.get(self.userid, 'username')
3924         # now verify the password supplied against the LDAP store
3927 Changes to Tracker Behaviour
3928 ----------------------------
3930 Preventing SPAM
3931 ~~~~~~~~~~~~~~~
3933 The following detector code may be installed in your tracker's
3934 ``detectors`` directory. It will block any messages being created that
3935 have HTML attachments (a very common vector for spam and phishing)
3936 and any messages that have more than 2 HTTP URLs in them. Just copy
3937 the following into ``detectors/anti_spam.py`` in your tracker::
3939     from roundup.exceptions import Reject
3941     def reject_html(db, cl, nodeid, newvalues):
3942         if newvalues['type'] == 'text/html':
3943         raise Reject, 'not allowed'
3945     def reject_manylinks(db, cl, nodeid, newvalues):
3946         content = newvalues['content']
3947         if content.count('http://') > 2:
3948         raise Reject, 'not allowed'
3950     def init(db):
3951         db.file.audit('create', reject_html)
3952         db.msg.audit('create', reject_manylinks)
3954 You may also wish to block image attachments if your tracker does not
3955 need that ability::
3957     if newvalues['type'].startswith('image/'):
3958         raise Reject, 'not allowed'
3961 Stop "nosy" messages going to people on vacation
3962 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3964 When users go on vacation and set up vacation email bouncing, you'll
3965 start to see a lot of messages come back through Roundup "Fred is on
3966 vacation". Not very useful, and relatively easy to stop.
3968 1. add a "vacation" flag to your users::
3970          user = Class(db, "user",
3971                     username=String(),   password=Password(),
3972                     address=String(),    realname=String(),
3973                     phone=String(),      organisation=String(),
3974                     alternate_addresses=String(),
3975                     roles=String(), queries=Multilink("query"),
3976                     vacation=Boolean())
3978 2. So that users may edit the vacation flags, add something like the
3979    following to your ``user.item`` template::
3981      <tr>
3982       <th>On Vacation</th> 
3983       <td tal:content="structure context/vacation/field">vacation</td> 
3984      </tr> 
3986 3. edit your detector ``nosyreactor.py`` so that the ``nosyreaction()``
3987    consists of::
3989     def nosyreaction(db, cl, nodeid, oldvalues):
3990         users = db.user
3991         messages = db.msg
3992         # send a copy of all new messages to the nosy list
3993         for msgid in determineNewMessages(cl, nodeid, oldvalues):
3994             try:
3995                 # figure the recipient ids
3996                 sendto = []
3997                 seen_message = {}
3998                 recipients = messages.get(msgid, 'recipients')
3999                 for recipid in messages.get(msgid, 'recipients'):
4000                     seen_message[recipid] = 1
4002                 # figure the author's id, and indicate they've received
4003                 # the message
4004                 authid = messages.get(msgid, 'author')
4006                 # possibly send the message to the author, as long as
4007                 # they aren't anonymous
4008                 if (db.config.MESSAGES_TO_AUTHOR == 'yes' and
4009                         users.get(authid, 'username') != 'anonymous'):
4010                     sendto.append(authid)
4011                 seen_message[authid] = 1
4013                 # now figure the nosy people who weren't recipients
4014                 nosy = cl.get(nodeid, 'nosy')
4015                 for nosyid in nosy:
4016                     # Don't send nosy mail to the anonymous user (that
4017                     # user shouldn't appear in the nosy list, but just
4018                     # in case they do...)
4019                     if users.get(nosyid, 'username') == 'anonymous':
4020                         continue
4021                     # make sure they haven't seen the message already
4022                     if not seen_message.has_key(nosyid):
4023                         # send it to them
4024                         sendto.append(nosyid)
4025                         recipients.append(nosyid)
4027                 # generate a change note
4028                 if oldvalues:
4029                     note = cl.generateChangeNote(nodeid, oldvalues)
4030                 else:
4031                     note = cl.generateCreateNote(nodeid)
4033                 # we have new recipients
4034                 if sendto:
4035                     # filter out the people on vacation
4036                     sendto = [i for i in sendto 
4037                               if not users.get(i, 'vacation', 0)]
4039                     # map userids to addresses
4040                     sendto = [users.get(i, 'address') for i in sendto]
4042                     # update the message's recipients list
4043                     messages.set(msgid, recipients=recipients)
4045                     # send the message
4046                     cl.send_message(nodeid, msgid, note, sendto)
4047             except roundupdb.MessageSendError, message:
4048                 raise roundupdb.DetectorError, message
4050    Note that this is the standard nosy reaction code, with the small
4051    addition of::
4053     # filter out the people on vacation
4054     sendto = [i for i in sendto if not users.get(i, 'vacation', 0)]
4056    which filters out the users that have the vacation flag set to true.
4058 Adding in state transition control
4059 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4061 Sometimes tracker admins want to control the states to which users may
4062 move issues. You can do this by following these steps:
4064 1. make "status" a required variable. This is achieved by adding the
4065    following to the top of the form in the ``issue.item.html``
4066    template::
4068      <input type="hidden" name="@required" value="status">
4070    This will force users to select a status.
4072 2. add a Multilink property to the status class::
4074      stat = Class(db, "status", ... , transitions=Multilink('status'),
4075                   ...)
4077    and then edit the statuses already created, either:
4079    a. through the web using the class list -> status class editor, or
4080    b. using the ``roundup-admin`` "set" command.
4082 3. add an auditor module ``checktransition.py`` in your tracker's
4083    ``detectors`` directory, for example::
4085      def checktransition(db, cl, nodeid, newvalues):
4086          ''' Check that the desired transition is valid for the "status"
4087              property.
4088          '''
4089          if not newvalues.has_key('status'):
4090              return
4091          current = cl.get(nodeid, 'status')
4092          new = newvalues['status']
4093          if new == current:
4094              return
4095          ok = db.status.get(current, 'transitions')
4096          if new not in ok:
4097              raise ValueError, 'Status not allowed to move from "%s" to "%s"'%(
4098                  db.status.get(current, 'name'), db.status.get(new, 'name'))
4100      def init(db):
4101          db.issue.audit('set', checktransition)
4103 4. in the ``issue.item.html`` template, change the status editing bit
4104    from::
4106     <th>Status</th>
4107     <td tal:content="structure context/status/menu">status</td>
4109    to::
4111     <th>Status</th>
4112     <td>
4113      <select tal:condition="context/id" name="status">
4114       <tal:block tal:define="ok context/status/transitions"
4115                  tal:repeat="state db/status/list">
4116        <option tal:condition="python:state.id in ok"
4117                tal:attributes="
4118                     value state/id;
4119                     selected python:state.id == context.status.id"
4120                tal:content="state/name"></option>
4121       </tal:block>
4122      </select>
4123      <tal:block tal:condition="not:context/id"
4124                 tal:replace="structure context/status/menu" />
4125     </td>
4127    which displays only the allowed status to transition to.
4130 Blocking issues that depend on other issues
4131 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4133 We needed the ability to mark certain issues as "blockers" - that is,
4134 they can't be resolved until another issue (the blocker) they rely on is
4135 resolved. To achieve this:
4137 1. Create a new property on the ``issue`` class:
4138    ``blockers=Multilink("issue")``. To do this, edit the definition of
4139    this class in your tracker's ``schema.py`` file. Change this::
4141     issue = IssueClass(db, "issue", 
4142                     assignedto=Link("user"), keyword=Multilink("keyword"),
4143                     priority=Link("priority"), status=Link("status"))
4145    to this, adding the blockers entry::
4147     issue = IssueClass(db, "issue", 
4148                     blockers=Multilink("issue"),
4149                     assignedto=Link("user"), keyword=Multilink("keyword"),
4150                     priority=Link("priority"), status=Link("status"))
4152 2. Add the new ``blockers`` property to the ``issue.item.html`` edit
4153    page, using something like::
4155     <th>Waiting On</th>
4156     <td>
4157      <span tal:replace="structure python:context.blockers.field(showid=1,
4158                                   size=20)" />
4159      <span tal:replace="structure python:db.issue.classhelp('id,title',
4160                                   property='blockers')" />
4161      <span tal:condition="context/blockers"
4162            tal:repeat="blk context/blockers">
4163       <br>View: <a tal:attributes="href string:issue${blk/id}"
4164                    tal:content="blk/id"></a>
4165      </span>
4166     </td>
4168    You'll need to fiddle with your item page layout to find an
4169    appropriate place to put it - I'll leave that fun part up to you.
4170    Just make sure it appears in the first table, possibly somewhere near
4171    the "superseders" field.
4173 3. Create a new detector module (see below) which enforces the rules:
4175    - issues may not be resolved if they have blockers
4176    - when a blocker is resolved, it's removed from issues it blocks
4178    The contents of the detector should be something like this::
4181     def blockresolution(db, cl, nodeid, newvalues):
4182         ''' If the issue has blockers, don't allow it to be resolved.
4183         '''
4184         if nodeid is None:
4185             blockers = []
4186         else:
4187             blockers = cl.get(nodeid, 'blockers')
4188         blockers = newvalues.get('blockers', blockers)
4190         # don't do anything if there's no blockers or the status hasn't
4191         # changed
4192         if not blockers or not newvalues.has_key('status'):
4193             return
4195         # get the resolved state ID
4196         resolved_id = db.status.lookup('resolved')
4198         # format the info
4199         u = db.config.TRACKER_WEB
4200         s = ', '.join(['<a href="%sissue%s">%s</a>'%(
4201                         u,id,id) for id in blockers])
4202         if len(blockers) == 1:
4203             s = 'issue %s is'%s
4204         else:
4205             s = 'issues %s are'%s
4207         # ok, see if we're trying to resolve
4208         if newvalues['status'] == resolved_id:
4209             raise ValueError, "This issue can't be resolved until %s resolved."%s
4212     def resolveblockers(db, cl, nodeid, oldvalues):
4213         ''' When we resolve an issue that's a blocker, remove it from the
4214             blockers list of the issue(s) it blocks.
4215         '''
4216         newstatus = cl.get(nodeid,'status')
4218         # no change?
4219         if oldvalues.get('status', None) == newstatus:
4220             return
4222         resolved_id = db.status.lookup('resolved')
4224         # interesting?
4225         if newstatus != resolved_id:
4226             return
4228         # yes - find all the blocked issues, if any, and remove me from
4229         # their blockers list
4230         issues = cl.find(blockers=nodeid)
4231         for issueid in issues:
4232             blockers = cl.get(issueid, 'blockers')
4233             if nodeid in blockers:
4234                 blockers.remove(nodeid)
4235                 cl.set(issueid, blockers=blockers)
4237     def init(db):
4238         # might, in an obscure situation, happen in a create
4239         db.issue.audit('create', blockresolution)
4240         db.issue.audit('set', blockresolution)
4242         # can only happen on a set
4243         db.issue.react('set', resolveblockers)
4245    Put the above code in a file called "blockers.py" in your tracker's
4246    "detectors" directory.
4248 4. Finally, and this is an optional step, modify the tracker web page
4249    URLs so they filter out issues with any blockers. You do this by
4250    adding an additional filter on "blockers" for the value "-1". For
4251    example, the existing "Show All" link in the "page" template (in the
4252    tracker's "html" directory) looks like this::
4254     <a href="#"
4255        tal:attributes="href python:request.indexargs_url('issue', {
4256       '@sort': '-activity',
4257       '@group': 'priority',
4258       '@filter': 'status',
4259       '@columns': columns_showall,
4260       '@search_text': '',
4261       'status': status_notresolved,
4262       '@dispname': i18n.gettext('Show All'),
4263      })"
4264        i18n:translate="">Show All</a><br>
4266    modify it to add the "blockers" info to the URL (note, both the
4267    "@filter" *and* "blockers" values must be specified)::
4269     <a href="#"
4270        tal:attributes="href python:request.indexargs_url('issue', {
4271       '@sort': '-activity',
4272       '@group': 'priority',
4273       '@filter': 'status,blockers',
4274       '@columns': columns_showall,
4275       '@search_text': '',
4276       'status': status_notresolved,
4277       'blockers': '-1',
4278       '@dispname': i18n.gettext('Show All'),
4279      })"
4280        i18n:translate="">Show All</a><br>
4282    The above examples are line-wrapped on the trailing & and should
4283    be unwrapped.
4285 That's it. You should now be able to set blockers on your issues. Note
4286 that if you want to know whether an issue has any other issues dependent
4287 on it (i.e. it's in their blockers list) you can look at the journal
4288 history at the bottom of the issue page - look for a "link" event to
4289 another issue's "blockers" property.
4291 Add users to the nosy list based on the keyword
4292 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4294 Let's say we need the ability to automatically add users to the nosy
4295 list based
4296 on the occurance of a keyword. Every user should be allowed to edit their
4297 own list of keywords for which they want to be added to the nosy list.
4299 Below, we'll show that this change can be done with minimal
4300 understanding of the Roundup system, using only copy and paste.
4302 This requires three changes to the tracker: a change in the database to
4303 allow per-user recording of the lists of keywords for which he wants to
4304 be put on the nosy list, a change in the user view allowing them to edit
4305 this list of keywords, and addition of an auditor which updates the nosy
4306 list when a keyword is set.
4308 Adding the nosy keyword list
4309 ::::::::::::::::::::::::::::
4311 The change to make in the database, is that for any user there should be a list
4312 of keywords for which he wants to be put on the nosy list. Adding a
4313 ``Multilink`` of ``keyword`` seems to fullfill this. As such, all that has to
4314 be done is to add a new field to the definition of ``user`` within the file
4315 ``schema.py``.  We will call this new field ``nosy_keywords``, and the updated
4316 definition of user will be::
4318     user = Class(db, "user", 
4319                     username=String(),   password=Password(),
4320                     address=String(),    realname=String(), 
4321                     phone=String(),      organisation=String(),
4322                     alternate_addresses=String(),
4323                     queries=Multilink('query'), roles=String(),
4324                     timezone=String(),
4325                     nosy_keywords=Multilink('keyword'))
4326  
4327 Changing the user view to allow changing the nosy keyword list
4328 ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
4330 We want any user to be able to change the list of keywords for which
4331 he will by default be added to the nosy list. We choose to add this
4332 to the user view, as is generated by the file ``html/user.item.html``.
4333 We can easily 
4334 see that the keyword field in the issue view has very similar editing
4335 requirements as our nosy keywords, both being lists of keywords. As
4336 such, we look for Keywords in ``issue.item.html``, and extract the
4337 associated parts from there. We add this to ``user.item.html`` at the 
4338 bottom of the list of viewed items (i.e. just below the 'Alternate
4339 E-mail addresses' in the classic template)::
4341  <tr>
4342   <th>Nosy Keywords</th>
4343   <td>
4344   <span tal:replace="structure context/nosy_keywords/field" />
4345   <span tal:replace="structure python:db.keyword.classhelp(property='nosy_keywords')" />
4346   </td>
4347  </tr>
4348   
4350 Addition of an auditor to update the nosy list
4351 ::::::::::::::::::::::::::::::::::::::::::::::
4353 The more difficult part is the logic to add
4354 the users to the nosy list when required. 
4355 We choose to perform this action whenever the keywords on an
4356 item are set (this includes the creation of items).
4357 Here we choose to start out with a copy of the 
4358 ``detectors/nosyreaction.py`` detector, which we copy to the file
4359 ``detectors/nosy_keyword_reaction.py``. 
4360 This looks like a good start as it also adds users
4361 to the nosy list. A look through the code reveals that the
4362 ``nosyreaction`` function actually sends the e-mail. 
4363 We don't need this. Therefore, we can change the ``init`` function to::
4365     def init(db):
4366         db.issue.audit('create', update_kw_nosy)
4367         db.issue.audit('set', update_kw_nosy)
4369 After that, we rename the ``updatenosy`` function to ``update_kw_nosy``.
4370 The first two blocks of code in that function relate to setting
4371 ``current`` to a combination of the old and new nosy lists. This
4372 functionality is left in the new auditor. The following block of
4373 code, which handled adding the assignedto user(s) to the nosy list in
4374 ``updatenosy``, should be replaced by a block of code to add the
4375 interested users to the nosy list. We choose here to loop over all
4376 new keywords, than looping over all users,
4377 and assign the user to the nosy list when the keyword occurs in the user's
4378 ``nosy_keywords``. The next part in ``updatenosy`` -- adding the author
4379 and/or recipients of a message to the nosy list -- is obviously not
4380 relevant here and is thus deleted from the new auditor. The last
4381 part, copying the new nosy list to ``newvalues``, can stay as is.
4382 This results in the following function::
4384     def update_kw_nosy(db, cl, nodeid, newvalues):
4385         '''Update the nosy list for changes to the keywords
4386         '''
4387         # nodeid will be None if this is a new node
4388         current = {}
4389         if nodeid is None:
4390             ok = ('new', 'yes')
4391         else:
4392             ok = ('yes',)
4393             # old node, get the current values from the node if they haven't
4394             # changed
4395             if not newvalues.has_key('nosy'):
4396                 nosy = cl.get(nodeid, 'nosy')
4397                 for value in nosy:
4398                     if not current.has_key(value):
4399                         current[value] = 1
4401         # if the nosy list changed in this transaction, init from the new value
4402         if newvalues.has_key('nosy'):
4403             nosy = newvalues.get('nosy', [])
4404             for value in nosy:
4405                 if not db.hasnode('user', value):
4406                     continue
4407                 if not current.has_key(value):
4408                     current[value] = 1
4410         # add users with keyword in nosy_keywords to the nosy list
4411         if newvalues.has_key('keyword') and newvalues['keyword'] is not None:
4412             keyword_ids = newvalues['keyword']
4413             for keyword in keyword_ids:
4414                 # loop over all users,
4415                 # and assign user to nosy when keyword in nosy_keywords
4416                 for user_id in db.user.list():
4417                     nosy_kw = db.user.get(user_id, "nosy_keywords")
4418                     found = 0
4419                     for kw in nosy_kw:
4420                         if kw == keyword:
4421                             found = 1
4422                     if found:
4423                         current[user_id] = 1
4425         # that's it, save off the new nosy list
4426         newvalues['nosy'] = current.keys()
4428 These two function are the only ones needed in the file.
4430 TODO: update this example to use the ``find()`` Class method.
4432 Caveats
4433 :::::::
4435 A few problems with the design here can be noted:
4437 Multiple additions
4438     When a user, after automatic selection, is manually removed
4439     from the nosy list, he is added to the nosy list again when the
4440     keyword list of the issue is updated. A better design might be
4441     to only check which keywords are new compared to the old list
4442     of keywords, and only add users when they have indicated
4443     interest on a new keyword.
4445     The code could also be changed to only trigger on the ``create()``
4446     event, rather than also on the ``set()`` event, thus only setting
4447     the nosy list when the issue is created.
4449 Scalability
4450     In the auditor, there is a loop over all users. For a site with
4451     only few users this will pose no serious problem; however, with
4452     many users this will be a serious performance bottleneck.
4453     A way out would be to link from the keywords to the users who
4454     selected these keywords as nosy keywords. This will eliminate the
4455     loop over all users.
4457 Changes to Security and Permissions
4458 -----------------------------------
4460 Restricting the list of users that are assignable to a task
4461 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4463 1. In your tracker's ``schema.py``, create a new Role, say "Developer"::
4465      db.security.addRole(name='Developer', description='A developer')
4467 2. Just after that, create a new Permission, say "Fixer", specific to
4468    "issue"::
4470      p = db.security.addPermission(name='Fixer', klass='issue',
4471          description='User is allowed to be assigned to fix issues')
4473 3. Then assign the new Permission to your "Developer" Role::
4475      db.security.addPermissionToRole('Developer', p)
4477 4. In the issue item edit page (``html/issue.item.html`` in your tracker
4478    directory), use the new Permission in restricting the "assignedto"
4479    list::
4481     <select name="assignedto">
4482      <option value="-1">- no selection -</option>
4483      <tal:block tal:repeat="user db/user/list">
4484      <option tal:condition="python:user.hasPermission(
4485                                 'Fixer', context._classname)"
4486              tal:attributes="
4487                 value user/id;
4488                 selected python:user.id == context.assignedto"
4489              tal:content="user/realname"></option>
4490      </tal:block>
4491     </select>
4493 For extra security, you may wish to setup an auditor to enforce the
4494 Permission requirement (install this as ``assignedtoFixer.py`` in your
4495 tracker ``detectors`` directory)::
4497   def assignedtoMustBeFixer(db, cl, nodeid, newvalues):
4498       ''' Ensure the assignedto value in newvalues is used with the
4499           Fixer Permission
4500       '''
4501       if not newvalues.has_key('assignedto'):
4502           # don't care
4503           return
4504   
4505       # get the userid
4506       userid = newvalues['assignedto']
4507       if not db.security.hasPermission('Fixer', userid, cl.classname):
4508           raise ValueError, 'You do not have permission to edit %s'%cl.classname
4510   def init(db):
4511       db.issue.audit('set', assignedtoMustBeFixer)
4512       db.issue.audit('create', assignedtoMustBeFixer)
4514 So now, if an edit action attempts to set "assignedto" to a user that
4515 doesn't have the "Fixer" Permission, the error will be raised.
4518 Users may only edit their issues
4519 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4521 In this case, users registering themselves are granted Provisional
4522 access, meaning they
4523 have access to edit the issues they submit, but not others. We create a new
4524 Role called "Provisional User" which is granted to newly-registered users,
4525 and has limited access. One of the Permissions they have is the new "Edit
4526 Own" on issues (regular users have "Edit".)
4528 First up, we create the new Role and Permission structure in
4529 ``schema.py``::
4531     #
4532     # New users not approved by the admin
4533     #
4534     db.security.addRole(name='Provisional User',
4535         description='New user registered via web or email')
4537     # These users need to be able to view and create issues but only edit
4538     # and view their own
4539     db.security.addPermissionToRole('Provisional User', 'Create', 'issue')
4540     def own_issue(db, userid, itemid):
4541         '''Determine whether the userid matches the creator of the issue.'''
4542         return userid == db.issue.get(itemid, 'creator')
4543     p = db.security.addPermission(name='Edit', klass='issue',
4544         check=own_issue, description='Can only edit own issues')
4545     db.security.addPermissionToRole('Provisional User', p)
4546     p = db.security.addPermission(name='View', klass='issue',
4547         check=own_issue, description='Can only view own issues')
4548     db.security.addPermissionToRole('Provisional User', p)
4550     # Assign the Permissions for issue-related classes
4551     for cl in 'file', 'msg', 'query', 'keyword':
4552         db.security.addPermissionToRole('Provisional User', 'View', cl)
4553         db.security.addPermissionToRole('Provisional User', 'Edit', cl)
4554         db.security.addPermissionToRole('Provisional User', 'Create', cl)
4555     for cl in 'priority', 'status':
4556         db.security.addPermissionToRole('Provisional User', 'View', cl)
4558     # and give the new users access to the web and email interface
4559     db.security.addPermissionToRole('Provisional User', 'Web Access')
4560     db.security.addPermissionToRole('Provisional User', 'Email Access')
4562     # make sure they can view & edit their own user record
4563     def own_record(db, userid, itemid):
4564         '''Determine whether the userid matches the item being accessed.'''
4565         return userid == itemid
4566     p = db.security.addPermission(name='View', klass='user', check=own_record,
4567         description="User is allowed to view their own user details")
4568     db.security.addPermissionToRole('Provisional User', p)
4569     p = db.security.addPermission(name='Edit', klass='user', check=own_record,
4570         description="User is allowed to edit their own user details")
4571     db.security.addPermissionToRole('Provisional User', p)
4573 Then, in ``config.ini``, we change the Role assigned to newly-registered
4574 users, replacing the existing ``'User'`` values::
4576     [main]
4577     ...
4578     new_web_user_roles = 'Provisional User'
4579     new_email_user_roles = 'Provisional User'
4582 All users may only view and edit issues, files and messages they create
4583 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4585 Replace the standard "classic" tracker View and Edit Permission assignments
4586 for the "issue", "file" and "msg" classes with the following::
4588     def checker(klass):
4589         def check(db, userid, itemid, klass=klass):
4590             return db.getclass(klass).get(itemid, 'creator') == userid
4591         return check
4592     for cl in 'issue', 'file', 'msg':
4593         p = db.security.addPermission(name='View', klass=cl,
4594             check=checker(cl))
4595         db.security.addPermissionToRole('User', p)
4596         p = db.security.addPermission(name='Edit', klass=cl,
4597             check=checker(cl))
4598         db.security.addPermissionToRole('User', p)
4599         db.security.addPermissionToRole('User', 'Create', cl)
4603 Changes to the Web User Interface
4604 ---------------------------------
4606 Adding action links to the index page
4607 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4609 Add a column to the ``item.index.html`` template.
4611 Resolving the issue::
4613   <a tal:attributes="href
4614      string:issue${i/id}?:status=resolved&:action=edit">resolve</a>
4616 "Take" the issue::
4618   <a tal:attributes="href
4619      string:issue${i/id}?:assignedto=${request/user/id}&:action=edit">take</a>
4621 ... and so on.
4623 Colouring the rows in the issue index according to priority
4624 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4626 A simple ``tal:attributes`` statement will do the bulk of the work here. In
4627 the ``issue.index.html`` template, add this to the ``<tr>`` that
4628 displays the rows of data::
4630    <tr tal:attributes="class string:priority-${i/priority/plain}">
4632 and then in your stylesheet (``style.css``) specify the colouring for the
4633 different priorities, as follows::
4635    tr.priority-critical td {
4636        background-color: red;
4637    }
4639    tr.priority-urgent td {
4640        background-color: orange;
4641    }
4643 and so on, with far less offensive colours :)
4645 Editing multiple items in an index view
4646 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4648 To edit the status of all items in the item index view, edit the
4649 ``issue.item.html``:
4651 1. add a form around the listing table (separate from the existing
4652    index-page form), so at the top it reads::
4654     <form method="POST" tal:attributes="action request/classname">
4655      <table class="list">
4657    and at the bottom of that table::
4659      </table>
4660     </form
4662    making sure you match the ``</table>`` from the list table, not the
4663    navigation table or the subsequent form table.
4665 2. in the display for the issue property, change::
4667     <td tal:condition="request/show/status"
4668         tal:content="python:i.status.plain() or default">&nbsp;</td>
4670    to::
4672     <td tal:condition="request/show/status"
4673         tal:content="structure i/status/field">&nbsp;</td>
4675    this will result in an edit field for the status property.
4677 3. after the ``tal:block`` which lists the index items (marked by
4678    ``tal:repeat="i batch"``) add a new table row::
4680     <tr>
4681      <td tal:attributes="colspan python:len(request.columns)">
4682       <input type="submit" value=" Save Changes ">
4683       <input type="hidden" name="@action" value="edit">
4684       <tal:block replace="structure request/indexargs_form" />
4685      </td>
4686     </tr>
4688    which gives us a submit button, indicates that we are performing an edit
4689    on any changed statuses. The final ``tal:block`` will make sure that the
4690    current index view parameters (filtering, columns, etc) will be used in 
4691    rendering the next page (the results of the editing).
4694 Displaying only message summaries in the issue display
4695 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4697 Alter the ``issue.item`` template section for messages to::
4699  <table class="messages" tal:condition="context/messages">
4700   <tr><th colspan="5" class="header">Messages</th></tr>
4701   <tr tal:repeat="msg context/messages">
4702    <td><a tal:attributes="href string:msg${msg/id}"
4703           tal:content="string:msg${msg/id}"></a></td>
4704    <td tal:content="msg/author">author</td>
4705    <td class="date" tal:content="msg/date/pretty">date</td>
4706    <td tal:content="msg/summary">summary</td>
4707    <td>
4708     <a tal:attributes="href string:?@remove@messages=${msg/id}&@action=edit">
4709     remove</a>
4710    </td>
4711   </tr>
4712  </table>
4715 Enabling display of either message summaries or the entire messages
4716 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4718 This is pretty simple - all we need to do is copy the code from the
4719 example `displaying only message summaries in the issue display`_ into
4720 our template alongside the summary display, and then introduce a switch
4721 that shows either the one or the other. We'll use a new form variable,
4722 ``@whole_messages`` to achieve this::
4724  <table class="messages" tal:condition="context/messages">
4725   <tal:block tal:condition="not:request/form/@whole_messages/value | python:0">
4726    <tr><th colspan="3" class="header">Messages</th>
4727        <th colspan="2" class="header">
4728          <a href="?@whole_messages=yes">show entire messages</a>
4729        </th>
4730    </tr>
4731    <tr tal:repeat="msg context/messages">
4732     <td><a tal:attributes="href string:msg${msg/id}"
4733            tal:content="string:msg${msg/id}"></a></td>
4734     <td tal:content="msg/author">author</td>
4735     <td class="date" tal:content="msg/date/pretty">date</td>
4736     <td tal:content="msg/summary">summary</td>
4737     <td>
4738      <a tal:attributes="href string:?@remove@messages=${msg/id}&@action=edit">remove</a>
4739     </td>
4740    </tr>
4741   </tal:block>
4743   <tal:block tal:condition="request/form/@whole_messages/value | python:0">
4744    <tr><th colspan="2" class="header">Messages</th>
4745        <th class="header">
4746          <a href="?@whole_messages=">show only summaries</a>
4747        </th>
4748    </tr>
4749    <tal:block tal:repeat="msg context/messages">
4750     <tr>
4751      <th tal:content="msg/author">author</th>
4752      <th class="date" tal:content="msg/date/pretty">date</th>
4753      <th style="text-align: right">
4754       (<a tal:attributes="href string:?@remove@messages=${msg/id}&@action=edit">remove</a>)
4755      </th>
4756     </tr>
4757     <tr><td colspan="3" tal:content="msg/content"></td></tr>
4758    </tal:block>
4759   </tal:block>
4760  </table>
4763 Setting up a "wizard" (or "druid") for controlled adding of issues
4764 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4766 1. Set up the page templates you wish to use for data input. My wizard
4767    is going to be a two-step process: first figuring out what category
4768    of issue the user is submitting, and then getting details specific to
4769    that category. The first page includes a table of help, explaining
4770    what the category names mean, and then the core of the form::
4772     <form method="POST" onSubmit="return submit_once()"
4773           enctype="multipart/form-data">
4774       <input type="hidden" name="@template" value="add_page1">
4775       <input type="hidden" name="@action" value="page1_submit">
4777       <strong>Category:</strong>
4778       <tal:block tal:replace="structure context/category/menu" />
4779       <input type="submit" value="Continue">
4780     </form>
4782    The next page has the usual issue entry information, with the
4783    addition of the following form fragments::
4785     <form method="POST" onSubmit="return submit_once()"
4786           enctype="multipart/form-data"
4787           tal:condition="context/is_edit_ok"
4788           tal:define="cat request/form/category/value">
4790       <input type="hidden" name="@template" value="add_page2">
4791       <input type="hidden" name="@required" value="title">
4792       <input type="hidden" name="category" tal:attributes="value cat">
4793        .
4794        .
4795        .
4796     </form>
4798    Note that later in the form, I use the value of "cat" to decide which
4799    form elements should be displayed. For example::
4801     <tal:block tal:condition="python:cat in '6 10 13 14 15 16 17'.split()">
4802      <tr>
4803       <th>Operating System</th>
4804       <td tal:content="structure context/os/field"></td>
4805      </tr>
4806      <tr>
4807       <th>Web Browser</th>
4808       <td tal:content="structure context/browser/field"></td>
4809      </tr>
4810     </tal:block>
4812    ... the above section will only be displayed if the category is one
4813    of 6, 10, 13, 14, 15, 16 or 17.
4815 3. Determine what actions need to be taken between the pages - these are
4816    usually to validate user choices and determine what page is next. Now encode
4817    those actions in a new ``Action`` class (see `defining new web actions`_)::
4819     from roundup.cgi.actions import Action
4821     class Page1SubmitAction(Action):
4822         def handle(self):
4823             ''' Verify that the user has selected a category, and then move
4824                 on to page 2.
4825             '''
4826             category = self.form['category'].value
4827             if category == '-1':
4828                 self.error_message.append('You must select a category of report')
4829                 return
4830             # everything's ok, move on to the next page
4831             self.template = 'add_page2'
4833     def init(instance):
4834         instance.registerAction('page1_submit', Page1SubmitAction)
4836 4. Use the usual "new" action as the ``@action`` on the final page, and
4837    you're done (the standard context/submit method can do this for you).
4840 Debugging Trackers
4841 ==================
4843 There are three switches in tracker configs that turn on debugging in
4844 Roundup:
4846 1. web :: debug
4847 2. mail :: debug
4848 3. logging :: level
4850 See the config.ini file or the `tracker configuration`_ section above for
4851 more information.
4853 Additionally, the ``roundup-server.py`` script has its own debugging mode
4854 in which it reloads edited templates immediately when they are changed,
4855 rather than requiring a web server restart.
4858 -------------------
4860 Back to `Table of Contents`_
4862 .. _`Table of Contents`: index.html
4863 .. _`design documentation`: design.html
4864 .. _`admin guide`: admin_guide.html