Code

084d334836944ca5f71ef6c666508b142d368861
[roundup.git] / doc / customizing.txt
1 ===================
2 Customising Roundup
3 ===================
5 :Version: $Revision: 1.123 $
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`_ file 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.py           Holds the basic `tracker configuration`_                 
43 dbinit.py           Holds the `tracker schema`_                              
44 interfaces.py       Defines the Web and E-Mail interfaces for the tracker    
45 select_db.py        Selects the database back-end for the tracker            
46 db/                 Holds the tracker's database                             
47 db/files/           Holds the tracker's upload files and messages            
48 detectors/          Auditors and reactors for this tracker                   
49 html/               Web interface templates, images and style sheets         
50 =================== ======================================================== 
52 Tracker Configuration
53 =====================
55 The ``config.py`` located in your tracker home contains the basic
56 configuration for the web and e-mail components of roundup's interfaces.
57 As the name suggests, this file is a Python module. This means that any
58 valid python expression may be used in the file. Mostly though, you'll
59 be setting the configuration variables to string values. Python string
60 values must be quoted with either single or double quotes::
62    'this is a string'
63    "this is also a string - use it when the value has 'single quotes'"
64    this is not a string - it's not quoted
66 Python strings may use formatting that's almost identical to C string
67 formatting. The ``%`` operator is used to perform the formatting, like
68 so::
70     'roundup-admin@%s'%MAIL_DOMAIN
72 this will create a string ``'roundup-admin@tracker.domain.example'`` if
73 MAIL_DOMAIN is set to ``'tracker.domain.example'``.
75 You'll also note some values are set to::
77    os.path.join(TRACKER_HOME, 'db')
79 or similar. This creates a new string which holds the path to the
80 ``'db'`` directory in the TRACKER_HOME directory. This is just a
81 convenience so if the TRACKER_HOME changes you don't have to edit
82 multiple valoues.
84 The configuration variables available are:
86 **TRACKER_HOME** - ``os.path.split(__file__)[0]``
87  The tracker home directory. The above default code will automatically
88  determine the tracker home for you, so you can just leave it alone.
90 **MAILHOST** - ``'localhost'``
91  The SMTP mail host that roundup will use to send e-mail.
93 **MAILUSER** - ``()``
94  If your SMTP mail host requires a username and password for access, then
95  specify them here. eg. ``MAILUSER = ('username', 'password')``
97 **MAILHOST_TLS** - ``'no'``
98  If your SMTP mail host provides or requires TLS (Transport Layer
99  Security) then set ``MAILHOST_TLS = 'yes'``
101 **MAILHOST_TLS_KEYFILE** - ``''``
102  If you're using TLS, you may also set MAILHOST_TLS_KEYFILE to the name of
103  a PEM formatted file that contains your private key.
105 **MAILHOST_TLS_CERTFILE** - ``''``
106  If you're using TLS and have specified a MAILHOST_TLS_KEYFILE, you may
107  also set MAILHOST_TLS_CERTFILE to the name of a PEM formatted certificate
108  chain file.
110 **MAIL_DOMAIN** - ``'tracker.domain.example'``
111  The domain name used for email addresses.
113 **DATABASE** - ``os.path.join(TRACKER_HOME, 'db')``
114  This is the directory that the database is going to be stored in. By default
115  it is in the tracker home.
117 **TEMPLATES** - ``os.path.join(TRACKER_HOME, 'html')``
118  This is the directory that the HTML templates reside in. By default they are
119  in the tracker home.
121 **TRACKER_NAME** - ``'Roundup issue tracker'``
122  A descriptive name for your roundup tracker. This is sent out in e-mails and
123  appears in the heading of CGI pages.
125 **TRACKER_EMAIL** - ``'issue_tracker@%s'%MAIL_DOMAIN``
126  The email address that e-mail sent to roundup should go to. Think of it as the
127  tracker's personal e-mail address.
129 **TRACKER_WEB** - ``'http://tracker.example/cgi-bin/roundup.cgi/bugs/'``
130  The web address that the tracker is viewable at. This will be included in
131  information sent to users of the tracker. The URL **must** include the
132  cgi-bin part or anything else that is required to get to the home page of
133  the tracker. You **must** include a trailing '/' in the URL.
135 **ADMIN_EMAIL** - ``'roundup-admin@%s'%MAIL_DOMAIN``
136  The email address that roundup will complain to if it runs into trouble.
138 **EMAIL_FROM_TAG** - ``''``
139  Additional text to include in the "name" part of the ``From:`` address used
140  in nosy messages. If the sending user is "Foo Bar", the ``From:`` line is
141  usually::
143     "Foo Bar" <issue_tracker@tracker.example>
145  The EMAIL_FROM_TAG goes inside the "Foo Bar" quotes like so::
147     "Foo Bar EMAIL_FROM_TAG" <issue_tracker@tracker.example>
149 **ERROR_MESSAGES_TO** - ``'user'``, ``'dispatcher'`` or ``'both'``
150  Sends error messages to the dispatcher, user, or both. It will use the
151  ``DISPATCHER_EMAIL`` address if set, otherwise it'll use the
152  ``ADMIN_EMAIL`` address.
154 **DISPATCHER_EMAIL** - ``''``
155   The email address that Roundup will issue all error messages to. This is
156   also useful if you want to switch your 'new message' notification to
157   a central user. 
159 **MESSAGES_TO_AUTHOR** - ``'new'``, ``'yes'`` or``'no'``
160  Send nosy messages to the author of the message?
161  If 'new' is used, then the author will only be sent the message when the
162  message creates a new issue. If 'yes' then the author will always be sent
163  a copy of the message they wrote.
165 **ADD_AUTHOR_TO_NOSY** - ``'new'``, ``'yes'`` or ``'no'``
166  Does the author of a message get placed on the nosy list automatically?
167  If ``'new'`` is used, then the author will only be added when a message
168  creates a new issue. If ``'yes'``, then the author will be added on followups
169  too. If ``'no'``, they're never added to the nosy.
171 **ADD_RECIPIENTS_TO_NOSY** - ``'new'``, ``'yes'`` or ``'no'``
172  Do the recipients (To:, Cc:) of a message get placed on the nosy list?
173  If ``'new'`` is used, then the recipients will only be added when a message
174  creates a new issue. If ``'yes'``, then the recipients will be added on
175  followups too. If ``'no'``, they're never added to the nosy.
177 **EMAIL_SIGNATURE_POSITION** - ``'top'``, ``'bottom'`` or ``'none'``
178  Where to place the email signature in messages that Roundup generates.
180 **EMAIL_KEEP_QUOTED_TEXT** - ``'yes'`` or ``'no'``
181  Keep email citations. Citations are the part of e-mail which the sender has
182  quoted in their reply to previous e-mail with ``>`` or ``|`` characters at
183  the start of the line.
185 **EMAIL_LEAVE_BODY_UNCHANGED** - ``'no'``
186  Preserve the email body as is. Enabiling this will cause the entire message
187  body to be stored, including all citations, signatures and Outlook-quoted
188  sections (ie. "Original Message" blocks). It should be either ``'yes'``
189  or ``'no'``.
191 **MAIL_DEFAULT_CLASS** - ``'issue'`` or ``''``
192  Default class to use in the mailgw if one isn't supplied in email
193  subjects. To disable, comment out the variable below or leave it blank.
195 **HTML_VERSION** -  ``'html4'`` or ``'xhtml'``
196  HTML version to generate. The templates are html4 by default. If you
197  wish to make them xhtml, then you'll need to change this var to 'xhtml'
198  too so all auto-generated HTML is compliant.
200 **EMAIL_CHARSET** - ``utf-8`` (or ``iso-8859-1`` for Eudora users)
201  Character set to encode email headers with. We use utf-8 by default, as
202  it's the most flexible. Some mail readers (eg. Eudora) can't cope with
203  that, so you might need to specify a more limited character set (eg.
204  'iso-8859-1'.
206 The default config.py is given below - as you
207 can see, the MAIL_DOMAIN must be edited before any interaction with the
208 tracker is attempted.::
210     # roundup home is this package's directory
211     TRACKER_HOME=os.path.split(__file__)[0]
213     # The SMTP mail host that roundup will use to send mail
214     MAILHOST = 'localhost'
216     # The domain name used for email addresses.
217     MAIL_DOMAIN = 'your.tracker.email.domain.example'
219     # This is the directory that the database is going to be stored in
220     DATABASE = os.path.join(TRACKER_HOME, 'db')
222     # This is the directory that the HTML templates reside in
223     TEMPLATES = os.path.join(TRACKER_HOME, 'html')
225     # A descriptive name for your roundup tracker
226     TRACKER_NAME = 'Roundup issue tracker'
228     # The email address that mail to roundup should go to
229     TRACKER_EMAIL = 'issue_tracker@%s'%MAIL_DOMAIN
231     # The web address that the tracker is viewable at. This will be
232     # included in information sent to users of the tracker. The URL MUST
233     # include the cgi-bin part or anything else that is required to get
234     # to the home page of the tracker. You MUST include a trailing '/'
235     # in the URL.
236     TRACKER_WEB = 'http://tracker.example/cgi-bin/roundup.cgi/bugs/'
238     # The email address that roundup will complain to if it runs into
239     # trouble
240     ADMIN_EMAIL = 'roundup-admin@%s'%MAIL_DOMAIN
242     # Additional text to include in the "name" part of the From: address
243     # used in nosy messages. If the sending user is "Foo Bar", the From:
244     # line is usually: "Foo Bar" <issue_tracker@tracker.example>
245     # the EMAIL_FROM_TAG goes inside the "Foo Bar" quotes like so:
246     #    "Foo Bar EMAIL_FROM_TAG" <issue_tracker@tracker.example>
247     EMAIL_FROM_TAG = ""
249     # Send nosy messages to the author of the message
250     MESSAGES_TO_AUTHOR = 'no'           # either 'yes' or 'no'
252     # Does the author of a message get placed on the nosy list
253     # automatically? If 'new' is used, then the author will only be
254     # added when a message creates a new issue. If 'yes', then the
255     # author will be added on followups too. If 'no', they're never
256     # added to the nosy.
257     ADD_AUTHOR_TO_NOSY = 'new'          # one of 'yes', 'no', 'new'
259     # Do the recipients (To:, Cc:) of a message get placed on the nosy
260     # list? If 'new' is used, then the recipients will only be added
261     # when a message creates a new issue. If 'yes', then the recipients
262     # will be added on followups too. If 'no', they're never added to
263     # the nosy.
264     ADD_RECIPIENTS_TO_NOSY = 'new'      # either 'yes', 'no', 'new'
266     # Where to place the email signature
267     EMAIL_SIGNATURE_POSITION = 'bottom' # one of 'top', 'bottom', 'none'
269     # Keep email citations
270     EMAIL_KEEP_QUOTED_TEXT = 'no'       # either 'yes' or 'no'
272     # Preserve the email body as is
273     EMAIL_LEAVE_BODY_UNCHANGED = 'no'   # either 'yes' or 'no'
275     # Default class to use in the mailgw if one isn't supplied in email
276     # subjects. To disable, comment out the variable below or leave it
277     # blank. Examples:
278     MAIL_DEFAULT_CLASS = 'issue'   # use "issue" class by default
279     #MAIL_DEFAULT_CLASS = ''        # disable (or just comment the var out)
281     # HTML version to generate. The templates are html4 by default. If you
282     # wish to make them xhtml, then you'll need to change this var to 'xhtml'
283     # too so all auto-generated HTML is compliant.
284     HTML_VERSION = 'html4'         # either 'html4' or 'xhtml'
286     # Character set to encode email headers with. We use utf-8 by default, as
287     # it's the most flexible. Some mail readers (eg. Eudora) can't cope with
288     # that, so you might need to specify a more limited character set (eg.
289     # 'iso-8859-1'.
290     EMAIL_CHARSET = 'utf-8'
291     #EMAIL_CHARSET = 'iso-8859-1'   # use this instead for Eudora users
293     # 
294     # SECURITY DEFINITIONS
295     #
296     # define the Roles that a user gets when they register with the
297     # tracker these are a comma-separated string of role names (e.g.
298     # 'Admin,User')
299     NEW_WEB_USER_ROLES = 'User'
300     NEW_EMAIL_USER_ROLES = 'User'
302 Tracker Schema
303 ==============
305 Note: if you modify the schema, you'll most likely need to edit the
306       `web interface`_ HTML template files and `detectors`_ to reflect
307       your changes.
309 A tracker schema defines what data is stored in the tracker's database.
310 Schemas are defined using Python code in the ``dbinit.py`` module of your
311 tracker. The "classic" schema looks like this (see below for the meaning
312 of ``'setkey'``)::
314     pri = Class(db, "priority", name=String(), order=String())
315     pri.setkey("name")
317     stat = Class(db, "status", name=String(), order=String())
318     stat.setkey("name")
320     keyword = Class(db, "keyword", name=String())
321     keyword.setkey("name")
323     user = Class(db, "user", username=String(), organisation=String(),
324         password=String(), address=String(), realname=String(),
325         phone=String())
326     user.setkey("username")
328     msg = FileClass(db, "msg", author=Link("user"), summary=String(),
329         date=Date(), recipients=Multilink("user"),
330         files=Multilink("file"))
332     file = FileClass(db, "file", name=String(), type=String())
334     issue = IssueClass(db, "issue", topic=Multilink("keyword"),
335         status=Link("status"), assignedto=Link("user"),
336         priority=Link("priority"))
337     issue.setkey('title')
340 What you can't do to the schema
341 -------------------------------
343 You must never:
345 **Remove the users class**
346   This class is the only *required* class in Roundup. Similarly, its
347   username, password and address properties must never be removed.
349 **Change the type of a property**
350   Property types must *never* be changed - the database simply doesn't take
351   this kind of action into account. Note that you can't just remove a
352   property and re-add it as a new type either. If you wanted to make the
353   assignedto property a Multilink, you'd need to create a new property
354   assignedto_list and remove the old assignedto property.
357 What you can do to the schema
358 -----------------------------
360 Your schema may be changed at any time before or after the tracker has been
361 initialised (or used). You may:
363 **Add new properties to classes, or add whole new classes**
364   This is painless and easy to do - there are generally no repurcussions
365   from adding new information to a tracker's schema.
367 **Remove properties**
368   Removing properties is a little more tricky - you need to make sure that
369   the property is no longer used in the `web interface`_ *or* by the
370   detectors_.
374 Classes and Properties - creating a new information store
375 ---------------------------------------------------------
377 In the tracker above, we've defined 7 classes of information:
379   priority
380       Defines the possible levels of urgency for issues.
382   status
383       Defines the possible states of processing the issue may be in.
385   keyword
386       Initially empty, will hold keywords useful for searching issues.
388   user
389       Initially holding the "admin" user, will eventually have an entry
390       for all users using roundup.
392   msg
393       Initially empty, will hold all e-mail messages sent to or
394       generated by roundup.
396   file
397       Initially empty, will hold all files attached to issues.
399   issue
400       Initially empty, this is where the issue information is stored.
402 We define the "priority" and "status" classes to allow two things:
403 reduction in the amount of information stored on the issue and more
404 powerful, accurate searching of issues by priority and status. By only
405 requiring a link on the issue (which is stored as a single number) we
406 reduce the chance that someone mis-types a priority or status - or
407 simply makes a new one up.
410 Class and Items
411 ~~~~~~~~~~~~~~~
413 A Class defines a particular class (or type) of data that will be stored
414 in the database. A class comprises one or more properties, which gives
415 the information about the class items.
417 The actual data entered into the database, using ``class.create()``, are
418 called items. They have a special immutable property called ``'id'``. We
419 sometimes refer to this as the *itemid*.
422 Properties
423 ~~~~~~~~~~
425 A Class is comprised of one or more properties of the following types:
427 * String properties are for storing arbitrary-length strings.
428 * Password properties are for storing encoded arbitrary-length strings.
429   The default encoding is defined on the ``roundup.password.Password``
430   class.
431 * Date properties store date-and-time stamps. Their values are Timestamp
432   objects.
433 * Number properties store numeric values.
434 * Boolean properties store on/off, yes/no, true/false values.
435 * A Link property refers to a single other item selected from a
436   specified class. The class is part of the property; the value is an
437   integer, the id of the chosen item.
438 * A Multilink property refers to possibly many items in a specified
439   class. The value is a list of integers.
442 FileClass
443 ~~~~~~~~~
445 FileClasses save their "content" attribute off in a separate file from
446 the rest of the database. This reduces the number of large entries in
447 the database, which generally makes databases more efficient, and also
448 allows us to use command-line tools to operate on the files. They are
449 stored in the files sub-directory of the ``'db'`` directory in your
450 tracker.
453 IssueClass
454 ~~~~~~~~~~
456 IssueClasses automatically include the "messages", "files", "nosy", and
457 "superseder" properties.
459 The messages and files properties list the links to the messages and
460 files related to the issue. The nosy property is a list of links to
461 users who wish to be informed of changes to the issue - they get "CC'ed"
462 e-mails when messages are sent to or generated by the issue. The nosy
463 reactor (in the ``'detectors'`` directory) handles this action. The
464 superseder link indicates an issue which has superseded this one.
466 They also have the dynamically generated "creation", "activity" and
467 "creator" properties.
469 The value of the "creation" property is the date when an item was
470 created, and the value of the "activity" property is the date when any
471 property on the item was last edited (equivalently, these are the dates
472 on the first and last records in the item's journal). The "creator"
473 property holds a link to the user that created the issue.
476 setkey(property)
477 ~~~~~~~~~~~~~~~~
479 Select a String property of the class to be the key property. The key
480 property must be unique, and allows references to the items in the class
481 by the content of the key property. That is, we can refer to users by
482 their username: for example, let's say that there's an issue in roundup,
483 issue 23. There's also a user, richard, who happens to be user 2. To
484 assign an issue to him, we could do either of::
486      roundup-admin set issue23 assignedto=2
488 or::
490      roundup-admin set issue23 assignedto=richard
492 Note, the same thing can be done in the web and e-mail interfaces. 
494 If a class does not have an "order" property, the key is also used to
495 sort instances of the class when it is rendered in the user interface.
496 (If a class has no "order" property, sorting is by the labelproperty of
497 the class. This is computed, in order of precedence, as the key, the
498 "name", the "title", or the first property alphabetically.)
501 create(information)
502 ~~~~~~~~~~~~~~~~~~~
504 Create an item in the database. This is generally used to create items
505 in the "definitional" classes like "priority" and "status".
508 Examples of adding to your schema
509 ---------------------------------
511 TODO
514 Detectors - adding behaviour to your tracker
515 ============================================
516 .. _detectors:
518 Detectors are initialised every time you open your tracker database, so
519 you're free to add and remove them any time, even after the database is
520 initialised via the "roundup-admin initialise" command.
522 The detectors in your tracker fire *before* (**auditors**) and *after*
523 (**reactors**) changes to the contents of your database. They are Python
524 modules that sit in your tracker's ``detectors`` directory. You will
525 have some installed by default - have a look. You can write new
526 detectors or modify the existing ones. The existing detectors installed
527 for you are:
529 **nosyreaction.py**
530   This provides the automatic nosy list maintenance and email sending.
531   The nosy reactor (``nosyreaction``) fires when new messages are added
532   to issues. The nosy auditor (``updatenosy``) fires when issues are
533   changed, and figures out what changes need to be made to the nosy list
534   (such as adding new authors, etc.)
535 **statusauditor.py**
536   This provides the ``chatty`` auditor which changes the issue status
537   from ``unread`` or ``closed`` to ``chatting`` if new messages appear.
538   It also provides the ``presetunread`` auditor which pre-sets the
539   status to ``unread`` on new items if the status isn't explicitly
540   defined.
541 **messagesummary.py**
542   Generates the ``summary`` property for new messages based on the message
543   content.
544 **userauditor.py**
545   Verifies the content of some of the user fields (email addresses and
546   roles lists).
548 If you don't want this default behaviour, you're completely free to change
549 or remove these detectors.
551 See the detectors section in the `design document`__ for details of the
552 interface for detectors.
554 __ design.html
556 Sample additional detectors that have been found useful will appear in
557 the ``'detectors'`` directory of the Roundup distribution. If you want
558 to use one, copy it to the ``'detectors'`` of your tracker instance:
560 **newissuecopy.py**
561   This detector sends an email to a team address whenever a new issue is
562   created. The address is hard-coded into the detector, so edit it
563   before you use it (look for the text 'team@team.host') or you'll get
564   email errors!
566   The detector code::
568     from roundup import roundupdb
570     def newissuecopy(db, cl, nodeid, oldvalues):
571         ''' Copy a message about new issues to a team address.
572         '''
573         # so use all the messages in the create
574         change_note = cl.generateCreateNote(nodeid)
576         # send a copy to the nosy list
577         for msgid in cl.get(nodeid, 'messages'):
578             try:
579                 # note: last arg must be a list
580                 cl.send_message(nodeid, msgid, change_note,
581                     ['team@team.host'])
582             except roundupdb.MessageSendError, message:
583                 raise roundupdb.DetectorError, message
585     def init(db):
586         db.issue.react('create', newissuecopy)
589 Auditor or Reactor?
590 -------------------
592 Generally speaking, the following rules should be observed:
594 **Auditors**
595   Are used for `vetoing creation of or changes to items`_. They might
596   also make automatic changes to item properties.
597 **Reactors**
598   Detect changes in the database and react accordingly. They should avoid
599   making changes to the database where possible, as this could create
600   detector loops.
602 Vetoing creation of or changes to items
603 ---------------------------------------
605 Auditors may raise the ``Reject`` exception to prevent the creation of
606 or changes to items in the database.  The mail gateway, for example, will
607 not attach files or messages to issues when the creation of those files or
608 messages are prevented through the ``Reject`` exception. It'll also not create
609 users if that creation is ``Reject``'ed too.
611 To use, simply add at the top of your auditor::
613    from roundup.exceptions import Reject
615 And then when your rejection criteria have been detected, simply::
617    raise Reject
620 Database Content
621 ================
623 Note: if you modify the content of definitional classes, you'll most
624        likely need to edit the tracker `detectors`_ to reflect your
625        changes.
627 Customisation of the special "definitional" classes (eg. status,
628 priority, resolution, ...) may be done either before or after the
629 tracker is initialised. The actual method of doing so is completely
630 different in each case though, so be careful to use the right one.
632 **Changing content before tracker initialisation**
633     Edit the dbinit module in your tracker to alter the items created in
634     using the ``create()`` methods.
636 **Changing content after tracker initialisation**
637     As the "admin" user, click on the "class list" link in the web
638     interface to bring up a list of all database classes. Click on the
639     name of the class you wish to change the content of.
641     You may also use the ``roundup-admin`` interface's create, set and
642     retire methods to add, alter or remove items from the classes in
643     question.
645 See "`adding a new field to the classic schema`_" for an example that
646 requires database content changes.
649 Security / Access Controls
650 ==========================
652 A set of Permissions is built into the security module by default:
654 - Edit (everything)
655 - View (everything)
657 Every Class you define in your tracker's schema also gets an Edit and View
658 Permission of its own.
660 The default interfaces define:
662 - Web Registration
663 - Web Access
664 - Web Roles
665 - Email Registration
666 - Email Access
668 These are hooked into the default Roles:
670 - Admin (Edit everything, View everything, Web Roles)
671 - User (Web Access, Email Access)
672 - Anonymous (Web Registration, Email Registration)
674 And finally, the "admin" user gets the "Admin" Role, and the "anonymous"
675 user gets "Anonymous" assigned when the database is initialised on
676 installation. The two default schemas then define:
678 - Edit issue, View issue (both)
679 - Edit file, View file (both)
680 - Edit msg, View msg (both)
681 - Edit support, View support (extended only)
683 and assign those Permissions to the "User" Role. Put together, these
684 settings appear in the ``open()`` function of the tracker ``dbinit.py``
685 (the following is taken from the "minimal" template's ``dbinit.py``)::
687     #
688     # SECURITY SETTINGS
689     #
690     # and give the regular users access to the web and email interface
691     p = db.security.getPermission('Web Access')
692     db.security.addPermissionToRole('User', p)
693     p = db.security.getPermission('Email Access')
694     db.security.addPermissionToRole('User', p)
696     # May users view other user information? Comment these lines out
697     # if you don't want them to
698     p = db.security.getPermission('View', 'user')
699     db.security.addPermissionToRole('User', p)
701     # Assign the appropriate permissions to the anonymous user's
702     # Anonymous role. Choices here are:
703     # - Allow anonymous users to register through the web
704     p = db.security.getPermission('Web Registration')
705     db.security.addPermissionToRole('Anonymous', p)
706     # - Allow anonymous (new) users to register through the email
707     #   gateway
708     p = db.security.getPermission('Email Registration')
709     db.security.addPermissionToRole('Anonymous', p)
712 New User Roles
713 --------------
715 New users are assigned the Roles defined in the config file as:
717 - NEW_WEB_USER_ROLES
718 - NEW_EMAIL_USER_ROLES
721 Changing Access Controls
722 ------------------------
724 You may alter the configuration variables to change the Role that new
725 web or email users get, for example to not give them access to the web
726 interface if they register through email. 
728 You may use the ``roundup-admin`` "``security``" command to display the
729 current Role and Permission configuration in your tracker.
732 Adding a new Permission
733 ~~~~~~~~~~~~~~~~~~~~~~~
735 When adding a new Permission, you will need to:
737 1. add it to your tracker's dbinit so it is created, using
738    ``security.addPermission``, for example::
740     self.security.addPermission(name="View", klass='frozzle',
741         description="User is allowed to access frozzles")
743    will set up a new "View" permission on the Class "frozzle".
744 2. enable it for the Roles that should have it (verify with
745    "``roundup-admin security``")
746 3. add it to the relevant HTML interface templates
747 4. add it to the appropriate xxxPermission methods on in your tracker
748    interfaces module
751 Example Scenarios
752 ~~~~~~~~~~~~~~~~~
754 **automatic registration of users in the e-mail gateway**
755  By giving the "anonymous" user the "Email Registration" Role, any
756  unidentified user will automatically be registered with the tracker
757  (with no password, so they won't be able to log in through the web
758  until an admin sets their password). Note: this is the default
759  behaviour in the tracker templates that ship with Roundup.
761 **anonymous access through the e-mail gateway**
762  Give the "anonymous" user the "Email Access" and ("Edit", "issue")
763  Roles but do not not give them the "Email Registration" Role. This
764  means that when an unknown user sends email into the tracker, they're
765  automatically logged in as "anonymous". Since they don't have the
766  "Email Registration" Role, they won't be automatically registered, but
767  since "anonymous" has permission to use the gateway, they'll still be
768  able to submit issues. Note that the Sender information - their email
769  address - will not be available - they're *anonymous*.
771 **only developers may be assigned issues**
772  Create a new Permission called "Fixer" for the "issue" class. Create a
773  new Role "Developer" which has that Permission, and assign that to the
774  appropriate users. Filter the list of users available in the assignedto
775  list to include only those users. Enforce the Permission with an
776  auditor. See the example 
777  `restricting the list of users that are assignable to a task`_.
779 **only managers may sign off issues as complete**
780  Create a new Permission called "Closer" for the "issue" class. Create a
781  new Role "Manager" which has that Permission, and assign that to the
782  appropriate users. In your web interface, only display the "resolved"
783  issue state option when the user has the "Closer" Permissions. Enforce
784  the Permission with an auditor. This is very similar to the previous
785  example, except that the web interface check would look like::
787    <option tal:condition="python:request.user.hasPermission('Closer')"
788            value="resolved">Resolved</option>
789  
790 **don't give web access to users who register through email**
791  Create a new Role called "Email User" which has all the Permissions of
792  the normal "User" Role minus the "Web Access" Permission. This will
793  allow users to send in emails to the tracker, but not access the web
794  interface.
796 **let some users edit the details of all users**
797  Create a new Role called "User Admin" which has the Permission for
798  editing users::
800     db.security.addRole(name='User Admin', description='Managing users')
801     p = db.security.getPermission('Edit', 'user')
802     db.security.addPermissionToRole('User Admin', p)
804  and assign the Role to the users who need the permission.
807 Web Interface
808 =============
810 .. contents::
811    :local:
812    :depth: 1
814 The web interface is provided by the ``roundup.cgi.client`` module and
815 is used by ``roundup.cgi``, ``roundup-server`` and ``ZRoundup``
816 (``ZRoundup``  is broken, until further notice). In all cases, we
817 determine which tracker is being accessed (the first part of the URL
818 path inside the scope of the CGI handler) and pass control on to the
819 tracker ``interfaces.Client`` class - which uses the ``Client`` class
820 from ``roundup.cgi.client`` - which handles the rest of the access
821 through its ``main()`` method. This means that you can do pretty much
822 anything you want as a web interface to your tracker.
824 Repercussions of changing the tracker schema
825 ---------------------------------------------
827 If you choose to change the `tracker schema`_ you will need to ensure
828 the web interface knows about it:
830 1. Index, item and search pages for the relevant classes may need to
831    have properties added or removed,
832 2. The "page" template may require links to be changed, as might the
833    "home" page's content arguments.
835 How requests are processed
836 --------------------------
838 The basic processing of a web request proceeds as follows:
840 1. figure out who we are, defaulting to the "anonymous" user
841 2. figure out what the request is for - we call this the "context"
842 3. handle any requested action (item edit, search, ...)
843 4. render the template requested by the context, resulting in HTML
844    output
846 In some situations, exceptions occur:
848 - HTTP Redirect  (generally raised by an action)
849 - SendFile       (generally raised by ``determine_context``)
850     here we serve up a FileClass "content" property
851 - SendStaticFile (generally raised by ``determine_context``)
852     here we serve up a file from the tracker "html" directory
853 - Unauthorised   (generally raised by an action)
854     here the action is cancelled, the request is rendered and an error
855     message is displayed indicating that permission was not granted for
856     the action to take place
857 - NotFound       (raised wherever it needs to be)
858     this exception percolates up to the CGI interface that called the
859     client
861 Determining web context
862 -----------------------
864 To determine the "context" of a request, we look at the URL and the
865 special request variable ``@template``. The URL path after the tracker
866 identifier is examined. Typical URL paths look like:
868 1.  ``/tracker/issue``
869 2.  ``/tracker/issue1``
870 3.  ``/tracker/_file/style.css``
871 4.  ``/cgi-bin/roundup.cgi/tracker/file1``
872 5.  ``/cgi-bin/roundup.cgi/tracker/file1/kitten.png``
874 where the "tracker identifier" is "tracker" in the above cases. That means
875 we're looking at "issue", "issue1", "_file/style.css", "file1" and
876 "file1/kitten.png" in the cases above. The path is generally only one
877 entry long - longer paths are handled differently.
879 a. if there is no path, then we are in the "home" context.
880 b. if the path starts with "_file" (as in example 3,
881    "/tracker/_file/style.css"), then the additional path entry,
882    "style.css" specifies the filename of a static file we're to serve up
883    from the tracker "html" directory. Raises a SendStaticFile exception.
884 c. if there is something in the path (as in example 1, "issue"), it
885    identifies the tracker class we're to display.
886 d. if the path is an item designator (as in examples 2 and 4, "issue1"
887    and "file1"), then we're to display a specific item.
888 e. if the path starts with an item designator and is longer than one
889    entry (as in example 5, "file1/kitten.png"), then we're assumed to be
890    handling an item of a ``FileClass``, and the extra path information
891    gives the filename that the client is going to label the download
892    with (i.e. "file1/kitten.png" is nicer to download than "file1").
893    This raises a ``SendFile`` exception.
895 Both b. and e. stop before we bother to determine the template we're
896 going to use. That's because they don't actually use templates.
898 The template used is specified by the ``@template`` CGI variable, which
899 defaults to:
901 - only classname suplied:        "index"
902 - full item designator supplied: "item"
905 Performing actions in web requests
906 ----------------------------------
908 When a user requests a web page, they may optionally also request for an
909 action to take place. As described in `how requests are processed`_, the
910 action is performed before the requested page is generated. Actions are
911 triggered by using a ``@action`` CGI variable, where the value is one
912 of:
914 **login**
915  Attempt to log a user in.
917 **logout**
918  Log the user out - make them "anonymous".
920 **register**
921  Attempt to create a new user based on the contents of the form and then
922  log them in.
924 **edit**
925  Perform an edit of an item in the database. There are some `special form
926  variables`_ you may use.
928 **new**
929  Add a new item to the database. You may use the same `special form
930  variables`_ as in the "edit" action.
932 **retire**
933  Retire the item in the database.
935 **editCSV**
936  Performs an edit of all of a class' items in one go. See also the
937  *class*.csv templating method which generates the CSV data to be
938  edited, and the ``'_generic.index'`` template which uses both of these
939  features.
941 **search**
942  Mangle some of the form variables:
944  - Set the form ":filter" variable based on the values of the filter
945    variables - if they're set to anything other than "dontcare" then add
946    them to :filter.
948  - Also handle the ":queryname" variable and save off the query to the
949    user's query list.
951 Each of the actions is implemented by a corresponding ``*XxxAction*`` (where
952 "Xxx" is the name of the action) class in the ``roundup.cgi.actions`` module.
953 These classes are registered with ``roundup.cgi.client.Client`` which also
954 happens to be available in your tracker instance as ``interfaces.Client``. So
955 if you need to define new actions, you may add them there (see `defining new
956 web actions`_).
958 Each action class also has a ``*permission*`` method which determines whether
959 the action is permissible given the current user. The base permission checks
960 are:
962 **login**
963  Determine whether the user has permission to log in. Base behaviour is
964  to check the user has "Web Access".
965 **logout**
966  No permission checks are made.
967 **register**
968  Determine whether the user has permission to register. Base behaviour
969  is to check the user has the "Web Registration" Permission.
970 **edit**
971  Determine whether the user has permission to edit this item. Base
972  behaviour is to check whether the user can edit this class. If we're
973  editing the "user" class, users are allowed to edit their own details -
974  unless they try to edit the "roles" property, which requires the
975  special Permission "Web Roles".
976 **new**
977  Determine whether the user has permission to create (or edit) this
978  item. Base behaviour is to check the user can edit this class. No
979  additional property checks are made. Additionally, new user items may
980  be created if the user has the "Web Registration" Permission.
981 **editCSV**
982  Determine whether the user has permission to edit this class. Base
983  behaviour is to check whether the user may edit this class.
984 **search**
985  Determine whether the user has permission to search this class. Base
986  behaviour is to check whether the user may view this class.
989 Special form variables
990 ----------------------
992 Item properties and their values are edited with html FORM
993 variables and their values. You can:
995 - Change the value of some property of the current item.
996 - Create a new item of any class, and edit the new item's
997   properties,
998 - Attach newly created items to a multilink property of the
999   current item.
1000 - Remove items from a multilink property of the current item.
1001 - Specify that some properties are required for the edit
1002   operation to be successful.
1004 In the following, <bracketed> values are variable, "@" may be
1005 either ":" or "@", and other text "required" is fixed.
1007 Most properties are specified as form variables:
1009 ``<propname>``
1010   property on the current context item
1012 ``<designator>"@"<propname>``
1013   property on the indicated item (for editing related information)
1015 Designators name a specific item of a class.
1017 ``<classname><N>``
1018     Name an existing item of class <classname>.
1020 ``<classname>"-"<N>``
1021     Name the <N>th new item of class <classname>. If the form
1022     submission is successful, a new item of <classname> is
1023     created. Within the submitted form, a particular
1024     designator of this form always refers to the same new
1025     item.
1027 Once we have determined the "propname", we look at it to see
1028 if it's special:
1030 ``@required``
1031     The associated form value is a comma-separated list of
1032     property names that must be specified when the form is
1033     submitted for the edit operation to succeed.  
1035     When the <designator> is missing, the properties are
1036     for the current context item.  When <designator> is
1037     present, they are for the item specified by
1038     <designator>.
1040     The "@required" specifier must come before any of the
1041     properties it refers to are assigned in the form.
1043 ``@remove@<propname>=id(s)`` or ``@add@<propname>=id(s)``
1044     The "@add@" and "@remove@" edit actions apply only to
1045     Multilink properties.  The form value must be a
1046     comma-separate list of keys for the class specified by
1047     the simple form variable.  The listed items are added
1048     to (respectively, removed from) the specified
1049     property.
1051 ``@link@<propname>=<designator>``
1052     If the edit action is "@link@", the simple form
1053     variable must specify a Link or Multilink property.
1054     The form value is a comma-separated list of
1055     designators.  The item corresponding to each
1056     designator is linked to the property given by simple
1057     form variable.
1059 None of the above (ie. just a simple form value)
1060     The value of the form variable is converted
1061     appropriately, depending on the type of the property.
1063     For a Link('klass') property, the form value is a
1064     single key for 'klass', where the key field is
1065     specified in dbinit.py.  
1067     For a Multilink('klass') property, the form value is a
1068     comma-separated list of keys for 'klass', where the
1069     key field is specified in dbinit.py.  
1071     Note that for simple-form-variables specifiying Link
1072     and Multilink properties, the linked-to class must
1073     have a key field.
1075     For a String() property specifying a filename, the
1076     file named by the form value is uploaded. This means we
1077     try to set additional properties "filename" and "type" (if
1078     they are valid for the class).  Otherwise, the property
1079     is set to the form value.
1081     For Date(), Interval(), Boolean(), and Number()
1082     properties, the form value is converted to the
1083     appropriate
1085 Any of the form variables may be prefixed with a classname or
1086 designator.
1088 Two special form values are supported for backwards compatibility:
1090 @note
1091     This is equivalent to::
1093         @link@messages=msg-1
1094         msg-1@content=value
1096     except that in addition, the "author" and "date" properties of
1097     "msg-1" are set to the userid of the submitter, and the current
1098     time, respectively.
1100 @file
1101     This is equivalent to::
1103         @link@files=file-1
1104         file-1@content=value
1106     The String content value is handled as described above for file
1107     uploads.
1109 If both the "@note" and "@file" form variables are
1110 specified, the action::
1112         @link@msg-1@files=file-1
1114 is also performed.
1116 We also check that FileClass items have a "content" property with
1117 actual content, otherwise we remove them from all_props before
1118 returning.
1122 Default templates
1123 -----------------
1125 The default templates are html4 compliant. If you wish to change them to be
1126 xhtml compliant, you'll need to change the ``HTML_VERSION`` configuration
1127 variable in ``config.py`` to ``'xhtml'`` instead of ``'html4'``.
1129 Most customisation of the web view can be done by modifying the
1130 templates in the tracker ``'html'`` directory. There are several types
1131 of files in there. The *minimal* template includes:
1133 **page.html**
1134   This template usually defines the overall look of your tracker. When
1135   you view an issue, it appears inside this template. When you view an
1136   index, it also appears inside this template. This template defines a
1137   macro called "icing" which is used by almost all other templates as a
1138   coating for their content, using its "content" slot. It also defines
1139   the "head_title" and "body_title" slots to allow setting of the page
1140   title.
1141 **home.html**
1142   the default page displayed when no other page is indicated by the user
1143 **home.classlist.html**
1144   a special version of the default page that lists the classes in the
1145   tracker
1146 **classname.item.html**
1147   displays an item of the *classname* class
1148 **classname.index.html**
1149   displays a list of *classname* items
1150 **classname.search.html**
1151   displays a search page for *classname* items
1152 **_generic.index.html**
1153   used to display a list of items where there is no
1154   ``*classname*.index`` available
1155 **_generic.help.html**
1156   used to display a "class help" page where there is no
1157   ``*classname*.help``
1158 **user.register.html**
1159   a special page just for the user class, that renders the registration
1160   page
1161 **style.css.html**
1162   a static file that is served up as-is
1164 The *classic* template has a number of additional templates.
1166 Note: Remember that you can create any template extension you want to,
1167 so if you just want to play around with the templating for new issues,
1168 you can copy the current "issue.item" template to "issue.test", and then
1169 access the test template using the "@template" URL argument::
1171    http://your.tracker.example/tracker/issue?@template=test
1173 and it won't affect your users using the "issue.item" template.
1176 How the templates work
1177 ----------------------
1180 Basic Templating Actions
1181 ~~~~~~~~~~~~~~~~~~~~~~~~
1183 Roundup's templates consist of special attributes on the HTML tags.
1184 These attributes form the Template Attribute Language, or TAL. The basic
1185 TAL commands are:
1187 **tal:define="variable expression; variable expression; ..."**
1188    Define a new variable that is local to this tag and its contents. For
1189    example::
1191       <html tal:define="title request/description">
1192        <head><title tal:content="title"></title></head>
1193       </html>
1195    In this example, the variable "title" is defined as the result of the
1196    expression "request/description". The "tal:content" command inside the
1197    <html> tag may then use the "title" variable.
1199 **tal:condition="expression"**
1200    Only keep this tag and its contents if the expression is true. For
1201    example::
1203      <p tal:condition="python:request.user.hasPermission('View', 'issue')">
1204       Display some issue information.
1205      </p>
1207    In the example, the <p> tag and its contents are only displayed if
1208    the user has the "View" permission for issues. We consider the number
1209    zero, a blank string, an empty list, and the built-in variable
1210    nothing to be false values. Nearly every other value is true,
1211    including non-zero numbers, and strings with anything in them (even
1212    spaces!).
1214 **tal:repeat="variable expression"**
1215    Repeat this tag and its contents for each element of the sequence
1216    that the expression returns, defining a new local variable and a
1217    special "repeat" variable for each element. For example::
1219      <tr tal:repeat="u user/list">
1220       <td tal:content="u/id"></td>
1221       <td tal:content="u/username"></td>
1222       <td tal:content="u/realname"></td>
1223      </tr>
1225    The example would iterate over the sequence of users returned by
1226    "user/list" and define the local variable "u" for each entry.
1228 **tal:replace="expression"**
1229    Replace this tag with the result of the expression. For example::
1231     <span tal:replace="request/user/realname" />
1233    The example would replace the <span> tag and its contents with the
1234    user's realname. If the user's realname was "Bruce", then the
1235    resultant output would be "Bruce".
1237 **tal:content="expression"**
1238    Replace the contents of this tag with the result of the expression.
1239    For example::
1241     <span tal:content="request/user/realname">user's name appears here
1242     </span>
1244    The example would replace the contents of the <span> tag with the
1245    user's realname. If the user's realname was "Bruce" then the
1246    resultant output would be "<span>Bruce</span>".
1248 **tal:attributes="attribute expression; attribute expression; ..."**
1249    Set attributes on this tag to the results of expressions. For
1250    example::
1252      <a tal:attributes="href string:user${request/user/id}">My Details</a>
1254    In the example, the "href" attribute of the <a> tag is set to the
1255    value of the "string:user${request/user/id}" expression, which will
1256    be something like "user123".
1258 **tal:omit-tag="expression"**
1259    Remove this tag (but not its contents) if the expression is true. For
1260    example::
1262       <span tal:omit-tag="python:1">Hello, world!</span>
1264    would result in output of::
1266       Hello, world!
1268 Note that the commands on a given tag are evaulated in the order above,
1269 so *define* comes before *condition*, and so on.
1271 Additionally, you may include tags such as <tal:block>, which are
1272 removed from output. Its content is kept, but the tag itself is not (so
1273 don't go using any "tal:attributes" commands on it). This is useful for
1274 making arbitrary blocks of HTML conditional or repeatable (very handy
1275 for repeating multiple table rows, which would othewise require an
1276 illegal tag placement to effect the repeat).
1279 Templating Expressions
1280 ~~~~~~~~~~~~~~~~~~~~~~
1282 The expressions you may use in the attribute values may be one of the
1283 following forms:
1285 **Path Expressions** - eg. ``item/status/checklist``
1286    These are object attribute / item accesses. Roughly speaking, the
1287    path ``item/status/checklist`` is broken into parts ``item``,
1288    ``status`` and ``checklist``. The ``item`` part is the root of the
1289    expression. We then look for a ``status`` attribute on ``item``, or
1290    failing that, a ``status`` item (as in ``item['status']``). If that
1291    fails, the path expression fails. When we get to the end, the object
1292    we're left with is evaluated to get a string - if it is a method, it
1293    is called; if it is an object, it is stringified. Path expressions
1294    may have an optional ``path:`` prefix, but they are the default
1295    expression type, so it's not necessary.
1297    If an expression evaluates to ``default``, then the expression is
1298    "cancelled" - whatever HTML already exists in the template will
1299    remain (tag content in the case of ``tal:content``, attributes in the
1300    case of ``tal:attributes``).
1302    If an expression evaluates to ``nothing`` then the target of the
1303    expression is removed (tag content in the case of ``tal:content``,
1304    attributes in the case of ``tal:attributes`` and the tag itself in
1305    the case of ``tal:replace``).
1307    If an element in the path may not exist, then you can use the ``|``
1308    operator in the expression to provide an alternative. So, the
1309    expression ``request/form/foo/value | default`` would simply leave
1310    the current HTML in place if the "foo" form variable doesn't exist.
1312    You may use the python function ``path``, as in
1313    ``path("item/status")``, to embed path expressions in Python
1314    expressions.
1316 **String Expressions** - eg. ``string:hello ${user/name}`` 
1317    These expressions are simple string interpolations - though they can
1318    be just plain strings with no interpolation if you want. The
1319    expression in the ``${ ... }`` is just a path expression as above.
1321 **Python Expressions** - eg. ``python: 1+1`` 
1322    These expressions give the full power of Python. All the "root level"
1323    variables are available, so ``python:item.status.checklist()`` would
1324    be equivalent to ``item/status/checklist``, assuming that
1325    ``checklist`` is a method.
1327 Modifiers:
1329 **structure** - eg. ``structure python:msg.content.plain(hyperlink=1)``
1330    The result of expressions are normally *escaped* to be safe for HTML
1331    display (all "<", ">" and "&" are turned into special entities). The
1332    ``structure`` expression modifier turns off this escaping - the
1333    result of the expression is now assumed to be HTML, which is passed
1334    to the web browser for rendering.
1336 **not:** - eg. ``not:python:1=1``
1337    This simply inverts the logical true/false value of another
1338    expression.
1341 Template Macros
1342 ~~~~~~~~~~~~~~~
1344 Macros are used in Roundup to save us from repeating the same common
1345 page stuctures over and over. The most common (and probably only) macro
1346 you'll use is the "icing" macro defined in the "page" template.
1348 Macros are generated and used inside your templates using special
1349 attributes similar to the `basic templating actions`_. In this case,
1350 though, the attributes belong to the Macro Expansion Template Attribute
1351 Language, or METAL. The macro commands are:
1353 **metal:define-macro="macro name"**
1354   Define that the tag and its contents are now a macro that may be
1355   inserted into other templates using the *use-macro* command. For
1356   example::
1358     <html metal:define-macro="page">
1359      ...
1360     </html>
1362   defines a macro called "page" using the ``<html>`` tag and its
1363   contents. Once defined, macros are stored on the template they're
1364   defined on in the ``macros`` attribute. You can access them later on
1365   through the ``templates`` variable, eg. the most common
1366   ``templates/page/macros/icing`` to access the "page" macro of the
1367   "page" template.
1369 **metal:use-macro="path expression"**
1370   Use a macro, which is identified by the path expression (see above).
1371   This will replace the current tag with the identified macro contents.
1372   For example::
1374    <tal:block metal:use-macro="templates/page/macros/icing">
1375     ...
1376    </tal:block>
1378    will replace the tag and its contents with the "page" macro of the
1379    "page" template.
1381 **metal:define-slot="slot name"** and **metal:fill-slot="slot name"**
1382   To define *dynamic* parts of the macro, you define "slots" which may
1383   be filled when the macro is used with a *use-macro* command. For
1384   example, the ``templates/page/macros/icing`` macro defines a slot like
1385   so::
1387     <title metal:define-slot="head_title">title goes here</title>
1389   In your *use-macro* command, you may now use a *fill-slot* command
1390   like this::
1392     <title metal:fill-slot="head_title">My Title</title>
1394   where the tag that fills the slot completely replaces the one defined
1395   as the slot in the macro.
1397 Note that you may not mix METAL and TAL commands on the same tag, but
1398 TAL commands may be used freely inside METAL-using tags (so your
1399 *fill-slots* tags may have all manner of TAL inside them).
1402 Information available to templates
1403 ----------------------------------
1405 Note: this is implemented by
1406 ``roundup.cgi.templating.RoundupPageTemplate``
1408 The following variables are available to templates.
1410 **context**
1411   The current context. This is either None, a `hyperdb class wrapper`_
1412   or a `hyperdb item wrapper`_
1413 **request**
1414   Includes information about the current request, including:
1415    - the current index information (``filterspec``, ``filter`` args,
1416      ``properties``, etc) parsed out of the form. 
1417    - methods for easy filterspec link generation
1418    - *user*, the current user item as an HTMLItem instance
1419    - *form*
1420      The current CGI form information as a mapping of form argument name
1421      to value
1422 **config**
1423   This variable holds all the values defined in the tracker config.py
1424   file (eg. TRACKER_NAME, etc.)
1425 **db**
1426   The current database, used to access arbitrary database items.
1427 **templates**
1428   Access to all the tracker templates by name. Used mainly in
1429   *use-macro* commands.
1430 **utils**
1431   This variable makes available some utility functions like batching.
1432 **nothing**
1433   This is a special variable - if an expression evaluates to this, then
1434   the tag (in the case of a ``tal:replace``), its contents (in the case
1435   of ``tal:content``) or some attributes (in the case of
1436   ``tal:attributes``) will not appear in the the output. So, for
1437   example::
1439     <span tal:attributes="class nothing">Hello, World!</span>
1441   would result in::
1443     <span>Hello, World!</span>
1445 **default**
1446   Also a special variable - if an expression evaluates to this, then the
1447   existing HTML in the template will not be replaced or removed, it will
1448   remain. So::
1450     <span tal:replace="default">Hello, World!</span>
1452   would result in::
1454     <span>Hello, World!</span>
1457 The context variable
1458 ~~~~~~~~~~~~~~~~~~~~
1460 The *context* variable is one of three things based on the current
1461 context (see `determining web context`_ for how we figure this out):
1463 1. if we're looking at a "home" page, then it's None
1464 2. if we're looking at a specific hyperdb class, it's a
1465    `hyperdb class wrapper`_.
1466 3. if we're looking at a specific hyperdb item, it's a
1467    `hyperdb item wrapper`_.
1469 If the context is not None, we can access the properties of the class or
1470 item. The only real difference between cases 2 and 3 above are:
1472 1. the properties may have a real value behind them, and this will
1473    appear if the property is displayed through ``context/property`` or
1474    ``context/property/field``.
1475 2. the context's "id" property will be a false value in the second case,
1476    but a real, or true value in the third. Thus we can determine whether
1477    we're looking at a real item from the hyperdb by testing
1478    "context/id".
1480 Hyperdb class wrapper
1481 :::::::::::::::::::::
1483 Note: this is implemented by the ``roundup.cgi.templating.HTMLClass``
1484 class.
1486 This wrapper object provides access to a hyperb class. It is used
1487 primarily in both index view and new item views, but it's also usable
1488 anywhere else that you wish to access information about a class, or the
1489 items of a class, when you don't have a specific item of that class in
1490 mind.
1492 We allow access to properties. There will be no "id" property. The value
1493 accessed through the property will be the current value of the same name
1494 from the CGI form.
1496 There are several methods available on these wrapper objects:
1498 =========== =============================================================
1499 Method      Description
1500 =========== =============================================================
1501 properties  return a `hyperdb property wrapper`_ for all of this class's
1502             properties.
1503 list        lists all of the active (not retired) items in the class.
1504 csv         return the items of this class as a chunk of CSV text.
1505 propnames   lists the names of the properties of this class.
1506 filter      lists of items from this class, filtered and sorted by the
1507             current *request* filterspec/filter/sort/group args
1508 classhelp   display a link to a javascript popup containing this class'
1509             "help" template.
1510 submit      generate a submit button (and action hidden element)
1511 renderWith  render this class with the given template.
1512 history     returns 'New node - no history' :)
1513 is_edit_ok  is the user allowed to Edit the current class?
1514 is_view_ok  is the user allowed to View the current class?
1515 =========== =============================================================
1517 Note that if you have a property of the same name as one of the above
1518 methods, you'll need to access it using a python "item access"
1519 expression. For example::
1521    python:context['list']
1523 will access the "list" property, rather than the list method.
1526 Hyperdb item wrapper
1527 ::::::::::::::::::::
1529 Note: this is implemented by the ``roundup.cgi.templating.HTMLItem``
1530 class.
1532 This wrapper object provides access to a hyperb item.
1534 We allow access to properties. There will be no "id" property. The value
1535 accessed through the property will be the current value of the same name
1536 from the CGI form.
1538 There are several methods available on these wrapper objects:
1540 =============== ========================================================
1541 Method          Description
1542 =============== ========================================================
1543 submit          generate a submit button (and action hidden element)
1544 journal         return the journal of the current item (**not
1545                 implemented**)
1546 history         render the journal of the current item as HTML
1547 renderQueryForm specific to the "query" class - render the search form
1548                 for the query
1549 hasPermission   specific to the "user" class - determine whether the
1550                 user has a Permission
1551 is_edit_ok      is the user allowed to Edit the current item?
1552 is_view_ok      is the user allowed to View the current item?
1553 =============== ========================================================
1555 Note that if you have a property of the same name as one of the above
1556 methods, you'll need to access it using a python "item access"
1557 expression. For example::
1559    python:context['journal']
1561 will access the "journal" property, rather than the journal method.
1564 Hyperdb property wrapper
1565 ::::::::::::::::::::::::
1567 Note: this is implemented by subclasses of the
1568 ``roundup.cgi.templating.HTMLProperty`` class (``HTMLStringProperty``,
1569 ``HTMLNumberProperty``, and so on).
1571 This wrapper object provides access to a single property of a class. Its
1572 value may be either:
1574 1. if accessed through a `hyperdb item wrapper`_, then it's a value from
1575    the hyperdb
1576 2. if access through a `hyperdb class wrapper`_, then it's a value from
1577    the CGI form
1580 The property wrapper has some useful attributes:
1582 =============== ========================================================
1583 Attribute       Description
1584 =============== ========================================================
1585 _name           the name of the property
1586 _value          the value of the property if any - this is the actual
1587                 value retrieved from the hyperdb for this property
1588 =============== ========================================================
1590 There are several methods available on these wrapper objects:
1592 =========== ================================================================
1593 Method      Description
1594 =========== ================================================================
1595 plain       render a "plain" representation of the property. This method
1596             may take two arguments:
1598             escape
1599              If true, escape the text so it is HTML safe (default: no). The
1600              reason this defaults to off is that text is usually escaped
1601              at a later stage by the TAL commands, unless the "structure"
1602              option is used in the template. The following ``tal:content``
1603              expressions are all equivalent::
1604  
1605               "structure python:msg.content.plain(escape=1)"
1606               "python:msg.content.plain()"
1607               "msg/content/plain"
1608               "msg/content"
1610              Usually you'll only want to use the escape option in a
1611              complex expression.
1613             hyperlink
1614              If true, turn URLs, email addresses and hyperdb item
1615              designators in the text into hyperlinks (default: no). Note
1616              that you'll need to use the "structure" TAL option if you
1617              want to use this ``tal:content`` expression::
1618   
1619               "structure python:msg.content.plain(hyperlink=1)"
1621              Note also that the text is automatically HTML-escaped before
1622              the hyperlinking transformation.
1623 hyperlinked The same as msg.content.plain(hyperlink=1), but nicer::
1625               "structure msg/content/hyperlinked"
1627 field       render an appropriate form edit field for the property - for
1628             most types this is a text entry box, but for Booleans it's a
1629             tri-state yes/no/neither selection.
1630 stext       only on String properties - render the value of the property
1631             as StructuredText (requires the StructureText module to be
1632             installed separately)
1633 multiline   only on String properties - render a multiline form edit
1634             field for the property
1635 email       only on String properties - render the value of the property
1636             as an obscured email address
1637 confirm     only on Password properties - render a second form edit field
1638             for the property, used for confirmation that the user typed
1639             the password correctly. Generates a field with name
1640             "name:confirm".
1641 now         only on Date properties - return the current date as a new
1642             property
1643 reldate     only on Date properties - render the interval between the date
1644             and now
1645 local       only on Date properties - return this date as a new property
1646             with some timezone offset, for example::
1647             
1648                 python:context.creation.local(10)
1650             will render the date with a +10 hour offset.
1651 pretty      Date properties - render the date as "dd Mon YYYY" (eg. "19
1652             Mar 2004"). Takes an optional format argument, for example::
1654                 python:context.activity.pretty('%Y-%m-%d')
1656             Will format as "2004-03-19" instead.
1658             Interval properties - render the interval in a pretty
1659             format (eg. "yesterday")
1660 menu        only on Link and Multilink properties - render a form select
1661             list for this property
1662 reverse     only on Multilink properties - produce a list of the linked
1663             items in reverse order
1664 =========== ================================================================
1667 The request variable
1668 ~~~~~~~~~~~~~~~~~~~~
1670 Note: this is implemented by the ``roundup.cgi.templating.HTMLRequest``
1671 class.
1673 The request variable is packed with information about the current
1674 request.
1676 .. taken from ``roundup.cgi.templating.HTMLRequest`` docstring
1678 =========== ============================================================
1679 Variable    Holds
1680 =========== ============================================================
1681 form        the CGI form as a cgi.FieldStorage
1682 env         the CGI environment variables
1683 base        the base URL for this tracker
1684 user        a HTMLUser instance for this user
1685 classname   the current classname (possibly None)
1686 template    the current template (suffix, also possibly None)
1687 form        the current CGI form variables in a FieldStorage
1688 =========== ============================================================
1690 **Index page specific variables (indexing arguments)**
1692 =========== ============================================================
1693 Variable    Holds
1694 =========== ============================================================
1695 columns     dictionary of the columns to display in an index page
1696 show        a convenience access to columns - request/show/colname will
1697             be true if the columns should be displayed, false otherwise
1698 sort        index sort column (direction, column name)
1699 group       index grouping property (direction, column name)
1700 filter      properties to filter the index on
1701 filterspec  values to filter the index on
1702 search_text text to perform a full-text search on for an index
1703 =========== ============================================================
1705 There are several methods available on the request variable:
1707 =============== ========================================================
1708 Method          Description
1709 =============== ========================================================
1710 description     render a description of the request - handle for the
1711                 page title
1712 indexargs_form  render the current index args as form elements
1713 indexargs_url   render the current index args as a URL
1714 base_javascript render some javascript that is used by other components
1715                 of the templating
1716 batch           run the current index args through a filter and return a
1717                 list of items (see `hyperdb item wrapper`_, and
1718                 `batching`_)
1719 =============== ========================================================
1721 The form variable
1722 :::::::::::::::::
1724 The form variable is a bit special because it's actually a python
1725 FieldStorage object. That means that you have two ways to access its
1726 contents. For example, to look up the CGI form value for the variable
1727 "name", use the path expression::
1729    request/form/name/value
1731 or the python expression::
1733    python:request.form['name'].value
1735 Note the "item" access used in the python case, and also note the
1736 explicit "value" attribute we have to access. That's because the form
1737 variables are stored as MiniFieldStorages. If there's more than one
1738 "name" value in the form, then the above will break since
1739 ``request/form/name`` is actually a *list* of MiniFieldStorages. So it's
1740 best to know beforehand what you're dealing with.
1743 The db variable
1744 ~~~~~~~~~~~~~~~
1746 Note: this is implemented by the ``roundup.cgi.templating.HTMLDatabase``
1747 class.
1749 Allows access to all hyperdb classes as attributes of this variable. If
1750 you want access to the "user" class, for example, you would use::
1752   db/user
1753   python:db.user
1755 Also, the current id of the current user is available as
1756 ``db.getuid()``. This isn't so useful in templates (where you have
1757 ``request/user``), but it can be useful in detectors or interfaces.
1759 The access results in a `hyperdb class wrapper`_.
1762 The templates variable
1763 ~~~~~~~~~~~~~~~~~~~~~~
1765 Note: this is implemented by the ``roundup.cgi.templating.Templates``
1766 class.
1768 This variable doesn't have any useful methods defined. It supports being
1769 used in expressions to access the templates, and consequently the
1770 template macros. You may access the templates using the following path
1771 expression::
1773    templates/name
1775 or the python expression::
1777    templates[name]
1779 where "name" is the name of the template you wish to access. The
1780 template has one useful attribute, namely "macros". To access a specific
1781 macro (called "macro_name"), use the path expression::
1783    templates/name/macros/macro_name
1785 or the python expression::
1787    templates[name].macros[macro_name]
1790 The utils variable
1791 ~~~~~~~~~~~~~~~~~~
1793 Note: this is implemented by the
1794 ``roundup.cgi.templating.TemplatingUtils`` class, but it may be extended
1795 as described below.
1797 =============== ========================================================
1798 Method          Description
1799 =============== ========================================================
1800 Batch           return a batch object using the supplied list
1801 =============== ========================================================
1803 You may add additional utility methods by writing them in your tracker
1804 ``interfaces.py`` module's ``TemplatingUtils`` class. See `adding a time
1805 log to your issues`_ for an example. The TemplatingUtils class itself
1806 will have a single attribute, ``client``, which may be used to access
1807 the ``client.db`` when you need to perform arbitrary database queries.
1809 Batching
1810 ::::::::
1812 Use Batch to turn a list of items, or item ids of a given class, into a
1813 series of batches. Its usage is::
1815     python:utils.Batch(sequence, size, start, end=0, orphan=0,
1816     overlap=0)
1818 or, to get the current index batch::
1820     request/batch
1822 The parameters are:
1824 ========= ==============================================================
1825 Parameter  Usage
1826 ========= ==============================================================
1827 sequence  a list of HTMLItems
1828 size      how big to make the sequence.
1829 start     where to start (0-indexed) in the sequence.
1830 end       where to end (0-indexed) in the sequence.
1831 orphan    if the next batch would contain less items than this value,
1832           then it is combined with this batch
1833 overlap   the number of items shared between adjacent batches
1834 ========= ==============================================================
1836 All of the parameters are assigned as attributes on the batch object. In
1837 addition, it has several more attributes:
1839 =============== ========================================================
1840 Attribute       Description
1841 =============== ========================================================
1842 start           indicates the start index of the batch. *Note: unlike
1843                 the argument, is a 1-based index (I know, lame)*
1844 first           indicates the start index of the batch *as a 0-based
1845                 index*
1846 length          the actual number of elements in the batch
1847 sequence_length the length of the original, unbatched, sequence.
1848 =============== ========================================================
1850 And several methods:
1852 =============== ========================================================
1853 Method          Description
1854 =============== ========================================================
1855 previous        returns a new Batch with the previous batch settings
1856 next            returns a new Batch with the next batch settings
1857 propchanged     detect if the named property changed on the current item
1858                 when compared to the last item
1859 =============== ========================================================
1861 An example of batching::
1863  <table class="otherinfo">
1864   <tr><th colspan="4" class="header">Existing Keywords</th></tr>
1865   <tr tal:define="keywords db/keyword/list"
1866       tal:repeat="start python:range(0, len(keywords), 4)">
1867    <td tal:define="batch python:utils.Batch(keywords, 4, start)"
1868        tal:repeat="keyword batch" tal:content="keyword/name">
1869        keyword here</td>
1870   </tr>
1871  </table>
1873 ... which will produce a table with four columns containing the items of
1874 the "keyword" class (well, their "name" anyway).
1876 Displaying Properties
1877 ---------------------
1879 Properties appear in the user interface in three contexts: in indices,
1880 in editors, and as search arguments. For each type of property, there
1881 are several display possibilities. For example, in an index view, a
1882 string property may just be printed as a plain string, but in an editor
1883 view, that property may be displayed in an editable field.
1886 Index Views
1887 -----------
1889 This is one of the class context views. It is also the default view for
1890 classes. The template used is "*classname*.index".
1893 Index View Specifiers
1894 ~~~~~~~~~~~~~~~~~~~~~
1896 An index view specifier (URL fragment) looks like this (whitespace has
1897 been added for clarity)::
1899      /issue?status=unread,in-progress,resolved&
1900             topic=security,ui&
1901             :group=+priority&
1902             :sort==activity&
1903             :filters=status,topic&
1904             :columns=title,status,fixer
1906 The index view is determined by two parts of the specifier: the layout
1907 part and the filter part. The layout part consists of the query
1908 parameters that begin with colons, and it determines the way that the
1909 properties of selected items are displayed. The filter part consists of
1910 all the other query parameters, and it determines the criteria by which
1911 items are selected for display. The filter part is interactively
1912 manipulated with the form widgets displayed in the filter section. The
1913 layout part is interactively manipulated by clicking on the column
1914 headings in the table.
1916 The filter part selects the union of the sets of items with values
1917 matching any specified Link properties and the intersection of the sets
1918 of items with values matching any specified Multilink properties.
1920 The example specifies an index of "issue" items. Only items with a
1921 "status" of either "unread" or "in-progress" or "resolved" are
1922 displayed, and only items with "topic" values including both "security"
1923 and "ui" are displayed. The items are grouped by priority, arranged in
1924 ascending order; and within groups, sorted by activity, arranged in
1925 descending order. The filter section shows filters for the "status" and
1926 "topic" properties, and the table includes columns for the "title",
1927 "status", and "fixer" properties.
1929 Searching Views
1930 ---------------
1932 Note: if you add a new column to the ``:columns`` form variable
1933       potentials then you will need to add the column to the appropriate
1934       `index views`_ template so that it is actually displayed.
1936 This is one of the class context views. The template used is typically
1937 "*classname*.search". The form on this page should have "search" as its
1938 ``@action`` variable. The "search" action:
1940 - sets up additional filtering, as well as performing indexed text
1941   searching
1942 - sets the ``:filter`` variable correctly
1943 - saves the query off if ``:query_name`` is set.
1945 The search page should lay out any fields that you wish to allow the
1946 user to search on. If your schema contains a large number of properties,
1947 you should be wary of making all of those properties available for
1948 searching, as this can cause confusion. If the additional properties are
1949 Strings, consider having their value indexed, and then they will be
1950 searchable using the full text indexed search. This is both faster, and
1951 more useful for the end user.
1953 The two special form values on search pages which are handled by the
1954 "search" action are:
1956 :search_text
1957   Text with which to perform a search of the text index. Results from
1958   that search will be used to limit the results of other filters (using
1959   an intersection operation)
1960 :query_name
1961   If supplied, the search parameters (including :search_text) will be
1962   saved off as a the query item and registered against the user's
1963   queries property. Note that the *classic* template schema has this
1964   ability, but the *minimal* template schema does not.
1967 Item Views
1968 ----------
1970 The basic view of a hyperdb item is provided by the "*classname*.item"
1971 template. It generally has three sections; an "editor", a "spool" and a
1972 "history" section.
1975 Editor Section
1976 ~~~~~~~~~~~~~~
1978 The editor section is used to manipulate the item - it may be a static
1979 display if the user doesn't have permission to edit the item.
1981 Here's an example of a basic editor template (this is the default
1982 "classic" template issue item edit form - from the "issue.item.html"
1983 template)::
1985  <table class="form">
1986  <tr>
1987   <th>Title</th>
1988   <td colspan="3" tal:content="structure python:context.title.field(size=60)">title</td>
1989  </tr>
1990  
1991  <tr>
1992   <th>Priority</th>
1993   <td tal:content="structure context/priority/menu">priority</td>
1994   <th>Status</th>
1995   <td tal:content="structure context/status/menu">status</td>
1996  </tr>
1997  
1998  <tr>
1999   <th>Superseder</th>
2000   <td>
2001    <span tal:replace="structure python:context.superseder.field(showid=1, size=20)" />
2002    <span tal:replace="structure python:db.issue.classhelp('id,title')" />
2003    <span tal:condition="context/superseder">
2004     <br>View: <span tal:replace="structure python:context.superseder.link(showid=1)" />
2005    </span>
2006   </td>
2007   <th>Nosy List</th>
2008   <td>
2009    <span tal:replace="structure context/nosy/field" />
2010    <span tal:replace="structure python:db.user.classhelp('username,realname,address,phone')" />
2011   </td>
2012  </tr>
2013  
2014  <tr>
2015   <th>Assigned To</th>
2016   <td tal:content="structure context/assignedto/menu">
2017    assignedto menu
2018   </td>
2019   <td>&nbsp;</td>
2020   <td>&nbsp;</td>
2021  </tr>
2022  
2023  <tr>
2024   <th>Change Note</th>
2025   <td colspan="3">
2026    <textarea name=":note" wrap="hard" rows="5" cols="60"></textarea>
2027   </td>
2028  </tr>
2029  
2030  <tr>
2031   <th>File</th>
2032   <td colspan="3"><input type="file" name=":file" size="40"></td>
2033  </tr>
2034  
2035  <tr>
2036   <td>&nbsp;</td>
2037   <td colspan="3" tal:content="structure context/submit">
2038    submit button will go here
2039   </td>
2040  </tr>
2041  </table>
2044 When a change is submitted, the system automatically generates a message
2045 describing the changed properties. As shown in the example, the editor
2046 template can use the ":note" and ":file" fields, which are added to the
2047 standard changenote message generated by Roundup.
2050 Form values
2051 :::::::::::
2053 We have a number of ways to pull properties out of the form in order to
2054 meet the various needs of:
2056 1. editing the current item (perhaps an issue item)
2057 2. editing information related to the current item (eg. messages or
2058    attached files)
2059 3. creating new information to be linked to the current item (eg. time
2060    spent on an issue)
2062 In the following, ``<bracketed>`` values are variable, ":" may be one of
2063 ":" or "@", and other text ("required") is fixed.
2065 Properties are specified as form variables:
2067 ``<propname>``
2068   property on the current context item
2070 ``<designator>:<propname>``
2071   property on the indicated item (for editing related information)
2073 ``<classname>-<N>:<propname>``
2074   property on the Nth new item of classname (generally for creating new
2075   items to attach to the current item)
2077 Once we have determined the "propname", we check to see if it is one of
2078 the special form values:
2080 ``@required``
2081   The named property values must be supplied or a ValueError will be
2082   raised.
2084 ``@remove@<propname>=id(s)``
2085   The ids will be removed from the multilink property.
2087 ``:add:<propname>=id(s)``
2088   The ids will be added to the multilink property.
2090 ``:link:<propname>=<designator>``
2091   Used to add a link to new items created during edit. These are
2092   collected and returned in ``all_links``. This will result in an
2093   additional linking operation (either Link set or Multilink append)
2094   after the edit/create is done using ``all_props`` in ``_editnodes``.
2095   The <propname> on the current item will be set/appended the id of the
2096   newly created item of class <designator> (where <designator> must be
2097   <classname>-<N>).
2099 Any of the form variables may be prefixed with a classname or
2100 designator.
2102 Two special form values are supported for backwards compatibility:
2104 ``:note``
2105   create a message (with content, author and date), linked to the
2106   context item. This is ALWAYS designated "msg-1".
2107 ``:file``
2108   create a file, attached to the current item and any message created by
2109   :note. This is ALWAYS designated "file-1".
2112 Spool Section
2113 ~~~~~~~~~~~~~
2115 The spool section lists related information like the messages and files
2116 of an issue.
2118 TODO
2121 History Section
2122 ~~~~~~~~~~~~~~~
2124 The final section displayed is the history of the item - its database
2125 journal. This is generally generated with the template::
2127  <tal:block tal:replace="structure context/history" />
2129 *To be done:*
2131 *The actual history entries of the item may be accessed for manual
2132 templating through the "journal" method of the item*::
2134  <tal:block tal:repeat="entry context/journal">
2135   a journal entry
2136  </tal:block>
2138 *where each journal entry is an HTMLJournalEntry.*
2140 Defining new web actions
2141 ------------------------
2143 You may define new actions to be triggered by the ``@action`` form variable.
2144 These are added to the tracker ``interfaces.py`` as ``Action`` classes that get
2145 called by the the ``Client`` class.
2147 Adding action classes takes three steps; first you `define the new
2148 action class`_, then you `register the action class`_ with the cgi
2149 interface so it may be triggered by the ``@action`` form variable.
2150 Finally you `use the new action`_ in your HTML form.
2152 See "`setting up a "wizard" (or "druid") for controlled adding of
2153 issues`_" for an example.
2156 Define the new action class
2157 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2159 The action classes have the following interface::
2161  class MyAction(Action):
2162      def handle(self):
2163          ''' Perform some action. No return value is required.
2164          '''
2166 The *self.client* attribute is an instance of your tracker ``instance.Client``
2167 class - thus it's mostly implemented by ``roundup.cgi.client.Client``. See the
2168 docstring of that class for details of what it can do.
2170 The method will typically check the ``self.form`` variable's contents.
2171 It may then:
2173 - add information to ``self.client.ok_message`` or ``self.client.error_message``
2174 - change the ``self.client.template`` variable to alter what the user will see
2175   next
2176 - raise Unauthorised, SendStaticFile, SendFile, NotFound or Redirect
2177   exceptions (import them from roundup.cgi.exceptions)
2180 Register the action class
2181 ~~~~~~~~~~~~~~~~~~~~~~~~~~
2183 The class is now written, but isn't available to the user until you add it to
2184 the ``instance.Client`` class ``actions`` variable, like so::
2186     actions = client.Client.actions + (
2187         ('myaction', myActionClass),
2188     )
2190 This maps the action name "myaction" to the action class we defined.
2192 Use the new action
2193 ~~~~~~~~~~~~~~~~~~
2195 In your HTML form, add a hidden form element like so::
2197   <input type="hidden" name="@action" value="myaction">
2199 where "myaction" is the name you registered in the previous step.
2201 Actions may return content to the user
2202 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2204 Actions generally perform some database manipulation and then pass control
2205 on to the rendering of a template in the current context (see `Determining
2206 web context`_ for how that works.) Some actions will want to generate the
2207 actual content returned to the user. Action methods may return their own
2208 content string to be displayed to the user, overriding the templating step.
2209 In this situation, we assume that the content is HTML by default. You may
2210 override the content type indicated to the user by calling ``setHeader``::
2212    self.client.setHeader('Content-Type', 'text/csv')
2214 This example indicates that the value sent back to the user is actually
2215 comma-separated value content (eg. something to be loaded into a
2216 spreadsheet or database).
2219 Examples
2220 ========
2222 .. contents::
2223    :local:
2224    :depth: 1
2227 Adding a new field to the classic schema
2228 ----------------------------------------
2230 This example shows how to add a new constrained property (i.e. a
2231 selection of distinct values) to your tracker.
2234 Introduction
2235 ~~~~~~~~~~~~
2237 To make the classic schema of roundup useful as a TODO tracking system
2238 for a group of systems administrators, it needed an extra data field per
2239 issue: a category.
2241 This would let sysadmins quickly list all TODOs in their particular area
2242 of interest without having to do complex queries, and without relying on
2243 the spelling capabilities of other sysadmins (a losing proposition at
2244 best).
2247 Adding a field to the database
2248 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2250 This is the easiest part of the change. The category would just be a
2251 plain string, nothing fancy. To change what is in the database you need
2252 to add some lines to the ``open()`` function in ``dbinit.py``. Under the
2253 comment::
2255     # add any additional database schema configuration here
2257 add::
2259     category = Class(db, "category", name=String())
2260     category.setkey("name")
2262 Here we are setting up a chunk of the database which we are calling
2263 "category". It contains a string, which we are refering to as "name" for
2264 lack of a more imaginative title. (Since "name" is one of the properties
2265 that Roundup looks for on items if you do not set a key for them, it's
2266 probably a good idea to stick with it for new classes if at all
2267 appropriate.) Then we are setting the key of this chunk of the database
2268 to be that "name". This is equivalent to an index for database types.
2269 This also means that there can only be one category with a given name.
2271 Adding the above lines allows us to create categories, but they're not
2272 tied to the issues that we are going to be creating. It's just a list of
2273 categories off on its own, which isn't much use. We need to link it in
2274 with the issues. To do that, find the lines in the ``open()`` function
2275 in ``dbinit.py`` which set up the "issue" class, and then add a link to
2276 the category::
2278     issue = IssueClass(db, "issue", ... ,
2279         category=Multilink("category"), ... )
2281 The ``Multilink()`` means that each issue can have many categories. If
2282 you were adding something with a one-to-one relationship to issues (such
2283 as the "assignedto" property), use ``Link()`` instead.
2285 That is all you need to do to change the schema. The rest of the effort
2286 is fiddling around so you can actually use the new category.
2289 Populating the new category class
2290 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2292 If you haven't initialised the database with the roundup-admin
2293 "initialise" command, then you can add the following to the tracker
2294 ``dbinit.py`` in the ``init()`` function under the comment::
2296     # add any additional database create steps here - but only if you
2297     # haven't initialised the database with the admin "initialise" command
2299 Add::
2301      category = db.getclass('category')
2302      category.create(name="scipy", order="1")
2303      category.create(name="chaco", order="2")
2304      category.create(name="weave", order="3")
2306 If the database has already been initalised, then you need to use the
2307 ``roundup-admin`` tool::
2309      % roundup-admin -i <tracker home>
2310      Roundup <version> ready for input.
2311      Type "help" for help.
2312      roundup> create category name=scipy order=1
2313      1
2314      roundup> create category name=chaco order=1
2315      2
2316      roundup> create category name=weave order=1
2317      3
2318      roundup> exit...
2319      There are unsaved changes. Commit them (y/N)? y
2321 TODO: explain why order=1 in each case. Also, does key get set to "name"
2322 automatically when added via roundup-admin?
2325 Setting up security on the new objects
2326 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2328 By default only the admin user can look at and change objects. This
2329 doesn't suit us, as we want any user to be able to create new categories
2330 as required, and obviously everyone needs to be able to view the
2331 categories of issues for it to be useful.
2333 We therefore need to change the security of the category objects. This
2334 is also done in the ``open()`` function of ``dbinit.py``.
2336 There are currently two loops which set up permissions and then assign
2337 them to various roles. Simply add the new "category" to both lists::
2339     # new permissions for this schema
2340     for cl in 'issue', 'file', 'msg', 'user', 'category':
2341         db.security.addPermission(name="Edit", klass=cl,
2342             description="User is allowed to edit "+cl)
2343         db.security.addPermission(name="View", klass=cl,
2344             description="User is allowed to access "+cl)
2346     # Assign the access and edit permissions for issue, file and message
2347     # to regular users now
2348     for cl in 'issue', 'file', 'msg', 'category':
2349         p = db.security.getPermission('View', cl)
2350         db.security.addPermissionToRole('User', p)
2351         p = db.security.getPermission('Edit', cl)
2352         db.security.addPermissionToRole('User', p)
2354 So you are in effect doing the following (with 'cl' substituted by its
2355 value)::
2357     db.security.addPermission(name="Edit", klass='category',
2358         description="User is allowed to edit "+'category')
2359     db.security.addPermission(name="View", klass='category',
2360         description="User is allowed to access "+'category')
2362 which is creating two permission types; that of editing and viewing
2363 "category" objects respectively. Then the following lines assign those
2364 new permissions to the "User" role, so that normal users can view and
2365 edit "category" objects::
2367     p = db.security.getPermission('View', 'category')
2368     db.security.addPermissionToRole('User', p)
2370     p = db.security.getPermission('Edit', 'category')
2371     db.security.addPermissionToRole('User', p)
2373 This is all the work that needs to be done for the database. It will
2374 store categories, and let users view and edit them. Now on to the
2375 interface stuff.
2378 Changing the web left hand frame
2379 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2381 We need to give the users the ability to create new categories, and the
2382 place to put the link to this functionality is in the left hand function
2383 bar, under the "Issues" area. The file that defines how this area looks
2384 is ``html/page``, which is what we are going to be editing next.
2386 If you look at this file you can see that it contains a lot of
2387 "classblock" sections which are chunks of HTML that will be included or
2388 excluded in the output depending on whether the condition in the
2389 classblock is met. Under the end of the classblock for issue is where we
2390 are going to add the category code::
2392   <p class="classblock"
2393      tal:condition="python:request.user.hasPermission('View', 'category')">
2394    <b>Categories</b><br>
2395    <a tal:condition="python:request.user.hasPermission('Edit', 'category')"
2396       href="category?@template=item">New Category<br></a>
2397   </p>
2399 The first two lines is the classblock definition, which sets up a
2400 condition that only users who have "View" permission for the "category"
2401 object will have this section included in their output. Next comes a
2402 plain "Categories" header in bold. Everyone who can view categories will
2403 get that.
2405 Next comes the link to the editing area of categories. This link will
2406 only appear if the condition - that the user has "Edit" permissions for
2407 the "category" objects - is matched. If they do have permission then
2408 they will get a link to another page which will let the user add new
2409 categories.
2411 Note that if you have permission to *view* but not to *edit* categories,
2412 then all you will see is a "Categories" header with nothing underneath
2413 it. This is obviously not very good interface design, but will do for
2414 now. I just claim that it is so I can add more links in this section
2415 later on. However to fix the problem you could change the condition in
2416 the classblock statement, so that only users with "Edit" permission
2417 would see the "Categories" stuff.
2420 Setting up a page to edit categories
2421 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2423 We defined code in the previous section which let users with the
2424 appropriate permissions see a link to a page which would let them edit
2425 conditions. Now we have to write that page.
2427 The link was for the *item* template of the *category* object. This
2428 translates into Roundup looking for a file called ``category.item.html``
2429 in the ``html`` tracker directory. This is the file that we are going to
2430 write now.
2432 First we add an info tag in a comment which doesn't affect the outcome
2433 of the code at all, but is useful for debugging. If you load a page in a
2434 browser and look at the page source, you can see which sections come
2435 from which files by looking for these comments::
2437     <!-- category.item -->
2439 Next we need to add in the METAL macro stuff so we get the normal page
2440 trappings::
2442  <tal:block metal:use-macro="templates/page/macros/icing">
2443   <title metal:fill-slot="head_title">Category editing</title>
2444   <td class="page-header-top" metal:fill-slot="body_title">
2445    <h2>Category editing</h2>
2446   </td>
2447   <td class="content" metal:fill-slot="content">
2449 Next we need to setup up a standard HTML form, which is the whole
2450 purpose of this file. We link to some handy javascript which sends the
2451 form through only once. This is to stop users hitting the send button
2452 multiple times when they are impatient and thus having the form sent
2453 multiple times::
2455     <form method="POST" onSubmit="return submit_once()"
2456           enctype="multipart/form-data">
2458 Next we define some code which sets up the minimum list of fields that
2459 we require the user to enter. There will be only one field - "name" - so
2460 they better put something in it, otherwise the whole form is pointless::
2462     <input type="hidden" name="@required" value="name">
2464 To get everything to line up properly we will put everything in a table,
2465 and put a nice big header on it so the user has an idea what is
2466 happening::
2468     <table class="form">
2469      <tr><th class="header" colspan="2">Category</th></tr>
2471 Next, we need the field into which the user is going to enter the new
2472 category. The "context.name.field(size=60)" bit tells Roundup to
2473 generate a normal HTML field of size 60, and the contents of that field
2474 will be the "name" variable of the current context (which is
2475 "category"). The upshot of this is that when the user types something in
2476 to the form, a new category will be created with that name::
2478     <tr>
2479      <th>Name</th>
2480      <td tal:content="structure python:context.name.field(size=60)">
2481      name</td>
2482     </tr>
2484 Then a submit button so that the user can submit the new category::
2486     <tr>
2487      <td>&nbsp;</td>
2488      <td colspan="3" tal:content="structure context/submit">
2489       submit button will go here
2490      </td>
2491     </tr>
2493 Finally we finish off the tags we used at the start to do the METAL
2494 stuff::
2496   </td>
2497  </tal:block>
2499 So putting it all together, and closing the table and form we get::
2501  <!-- category.item -->
2502  <tal:block metal:use-macro="templates/page/macros/icing">
2503   <title metal:fill-slot="head_title">Category editing</title>
2504   <td class="page-header-top" metal:fill-slot="body_title">
2505    <h2>Category editing</h2>
2506   </td>
2507   <td class="content" metal:fill-slot="content">
2508    <form method="POST" onSubmit="return submit_once()"
2509          enctype="multipart/form-data">
2511     <table class="form">
2512      <tr><th class="header" colspan="2">Category</th></tr>
2514      <tr>
2515       <th>Name</th>
2516       <td tal:content="structure python:context.name.field(size=60)">
2517       name</td>
2518      </tr>
2520      <tr>
2521       <td>
2522         &nbsp;
2523         <input type="hidden" name="@required" value="name"> 
2524       </td>
2525       <td colspan="3" tal:content="structure context/submit">
2526        submit button will go here
2527       </td>
2528      </tr>
2529     </table>
2530    </form>
2531   </td>
2532  </tal:block>
2534 This is quite a lot to just ask the user one simple question, but there
2535 is a lot of setup for basically one line (the form line) to do its work.
2536 To add another field to "category" would involve one more line (well,
2537 maybe a few extra to get the formatting correct).
2540 Adding the category to the issue
2541 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2543 We now have the ability to create issues to our heart's content, but
2544 that is pointless unless we can assign categories to issues.  Just like
2545 the ``html/category.item.html`` file was used to define how to add a new
2546 category, the ``html/issue.item.html`` is used to define how a new issue
2547 is created.
2549 Just like ``category.issue.html`` this file defines a form which has a
2550 table to lay things out. It doesn't matter where in the table we add new
2551 stuff, it is entirely up to your sense of aesthetics::
2553    <th>Category</th>
2554    <td><span tal:replace="structure context/category/field" />
2555        <span tal:replace="structure db/category/classhelp" />
2556    </td>
2558 First, we define a nice header so that the user knows what the next
2559 section is, then the middle line does what we are most interested in.
2560 This ``context/category/field`` gets replaced by a field which contains
2561 the category in the current context (the current context being the new
2562 issue).
2564 The classhelp lines generate a link (labelled "list") to a popup window
2565 which contains the list of currently known categories.
2568 Searching on categories
2569 ~~~~~~~~~~~~~~~~~~~~~~~
2571 We can add categories, and create issues with categories. The next
2572 obvious thing that we would like to be able to do, would be to search
2573 for issues based on their category, so that, for example, anyone working
2574 on the web server could look at all issues in the category "Web".
2576 If you look for "Search Issues" in the 'html/page.html' file, you will
2577 find that it looks something like 
2578 ``<a href="issue?@template=search">Search Issues</a>``. This shows us
2579 that when you click on "Search Issues" it will be looking for a
2580 ``issue.search.html`` file to display. So that is the file that we will
2581 change.
2583 If you look at this file it should be starting to seem familiar, although it
2584 does use some new macros. You can add the new category search code anywhere you
2585 like within that form::
2587   <tr tal:define="name string:category;
2588                   db_klass string:category;
2589                   db_content string:name;">
2590     <th>Priority:</th>
2591     <td metal:use-macro="search_select"></td>
2592     <td metal:use-macro="column_input"></td>
2593     <td metal:use-macro="sort_input"></td>
2594     <td metal:use-macro="group_input"></td>
2595   </tr>
2597 The definitions in the <tr> opening tag are used by the macros:
2599 - search_select expands to a drop-down box with all categories using db_klass
2600   and db_content.
2601 - column_input expands to a checkbox for selecting what columns should be
2602   displayed.
2603 - sort_input expands to a radio button for selecting what property should be
2604   sorted on.
2605 - group_input expands to a radio button for selecting what property should be
2606   group on.
2608 The category search code above would expand to the following::
2610   <tr>
2611     <th>Category:</th>
2612     <td>
2613       <select name="category">
2614         <option value="">don't care</option>
2615         <option value="">------------</option>      
2616         <option value="1">scipy</option>
2617         <option value="2">chaco</option>
2618         <option value="3">weave</option>
2619       </select>
2620     </td>
2621     <td><input type="checkbox" name=":columns" value="category"></td>
2622     <td><input type="radio" name=":sort" value="category"></td>
2623     <td><input type="radio" name=":group" value="category"></td>
2624   </tr>
2626 Adding category to the default view
2627 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2629 We can now add categories, add issues with categories, and search for
2630 issues based on categories. This is everything that we need to do;
2631 however, there is some more icing that we would like. I think the
2632 category of an issue is important enough that it should be displayed by
2633 default when listing all the issues.
2635 Unfortunately, this is a bit less obvious than the previous steps. The
2636 code defining how the issues look is in ``html/issue.index.html``. This
2637 is a large table with a form down at the bottom for redisplaying and so
2638 forth. 
2640 Firstly we need to add an appropriate header to the start of the table::
2642     <th tal:condition="request/show/category">Category</th>
2644 The *condition* part of this statement is to avoid displaying the
2645 Category column if the user has selected not to see it.
2647 The rest of the table is a loop which will go through every issue that
2648 matches the display criteria. The loop variable is "i" - which means
2649 that every issue gets assigned to "i" in turn.
2651 The new part of code to display the category will look like this::
2653     <td tal:condition="request/show/category"
2654         tal:content="i/category"></td>
2656 The condition is the same as above: only display the condition when the
2657 user hasn't asked for it to be hidden. The next part is to set the
2658 content of the cell to be the category part of "i" - the current issue.
2660 Finally we have to edit ``html/page.html`` again. This time, we need to
2661 tell it that when the user clicks on "Unasigned Issues" or "All Issues",
2662 the category column should be included in the resulting list. If you
2663 scroll down the page file, you can see the links with lots of options.
2664 The option that we are interested in is the ``:columns=`` one which
2665 tells roundup which fields of the issue to display. Simply add
2666 "category" to that list and it all should work.
2669 Adding in state transition control
2670 ----------------------------------
2672 Sometimes tracker admins want to control the states that users may move
2673 issues to. You can do this by following these steps:
2675 1. make "status" a required variable. This is achieved by adding the
2676    following to the top of the form in the ``issue.item.html``
2677    template::
2679      <input type="hidden" name="@required" value="status">
2681    this will force users to select a status.
2683 2. add a Multilink property to the status class::
2685      stat = Class(db, "status", ... , transitions=Multilink('status'),
2686                   ...)
2688    and then edit the statuses already created, either:
2690    a. through the web using the class list -> status class editor, or
2691    b. using the roundup-admin "set" command.
2693 3. add an auditor module ``checktransition.py`` in your tracker's
2694    ``detectors`` directory, for example::
2696      def checktransition(db, cl, nodeid, newvalues):
2697          ''' Check that the desired transition is valid for the "status"
2698              property.
2699          '''
2700          if not newvalues.has_key('status'):
2701              return
2702          current = cl.get(nodeid, 'status')
2703          new = newvalues['status']
2704          if new == current:
2705              return
2706          ok = db.status.get(current, 'transitions')
2707          if new not in ok:
2708              raise ValueError, 'Status not allowed to move from "%s" to "%s"'%(
2709                  db.status.get(current, 'name'), db.status.get(new, 'name'))
2711      def init(db):
2712          db.issue.audit('set', checktransition)
2714 4. in the ``issue.item.html`` template, change the status editing bit
2715    from::
2717     <th>Status</th>
2718     <td tal:content="structure context/status/menu">status</td>
2720    to::
2722     <th>Status</th>
2723     <td>
2724      <select tal:condition="context/id" name="status">
2725       <tal:block tal:define="ok context/status/transitions"
2726                  tal:repeat="state db/status/list">
2727        <option tal:condition="python:state.id in ok"
2728                tal:attributes="
2729                     value state/id;
2730                     selected python:state.id == context.status.id"
2731                tal:content="state/name"></option>
2732       </tal:block>
2733      </select>
2734      <tal:block tal:condition="not:context/id"
2735                 tal:replace="structure context/status/menu" />
2736     </td>
2738    which displays only the allowed status to transition to.
2741 Displaying only message summaries in the issue display
2742 ------------------------------------------------------
2744 Alter the issue.item template section for messages to::
2746  <table class="messages" tal:condition="context/messages">
2747   <tr><th colspan="5" class="header">Messages</th></tr>
2748   <tr tal:repeat="msg context/messages">
2749    <td><a tal:attributes="href string:msg${msg/id}"
2750           tal:content="string:msg${msg/id}"></a></td>
2751    <td tal:content="msg/author">author</td>
2752    <td class="date" tal:content="msg/date/pretty">date</td>
2753    <td tal:content="msg/summary">summary</td>
2754    <td>
2755     <a tal:attributes="href string:?@remove@messages=${msg/id}&@action=edit">
2756     remove</a>
2757    </td>
2758   </tr>
2759  </table>
2761 Restricting the list of users that are assignable to a task
2762 -----------------------------------------------------------
2764 1. In your tracker's "dbinit.py", create a new Role, say "Developer"::
2766      db.security.addRole(name='Developer', description='A developer')
2768 2. Just after that, create a new Permission, say "Fixer", specific to
2769    "issue"::
2771      p = db.security.addPermission(name='Fixer', klass='issue',
2772          description='User is allowed to be assigned to fix issues')
2774 3. Then assign the new Permission to your "Developer" Role::
2776      db.security.addPermissionToRole('Developer', p)
2778 4. In the issue item edit page ("html/issue.item.html" in your tracker
2779    directory), use the new Permission in restricting the "assignedto"
2780    list::
2782     <select name="assignedto">
2783      <option value="-1">- no selection -</option>
2784      <tal:block tal:repeat="user db/user/list">
2785      <option tal:condition="python:user.hasPermission(
2786                                 'Fixer', context._classname)"
2787              tal:attributes="
2788                 value user/id;
2789                 selected python:user.id == context.assignedto"
2790              tal:content="user/realname"></option>
2791      </tal:block>
2792     </select>
2794 For extra security, you may wish to setup an auditor to enforce the
2795 Permission requirement (install this as "assignedtoFixer.py" in your
2796 tracker "detectors" directory)::
2798   def assignedtoMustBeFixer(db, cl, nodeid, newvalues):
2799       ''' Ensure the assignedto value in newvalues is a used with the
2800           Fixer Permission
2801       '''
2802       if not newvalues.has_key('assignedto'):
2803           # don't care
2804           return
2805   
2806       # get the userid
2807       userid = newvalues['assignedto']
2808       if not db.security.hasPermission('Fixer', userid, cl.classname):
2809           raise ValueError, 'You do not have permission to edit %s'%cl.classname
2811   def init(db):
2812       db.issue.audit('set', assignedtoMustBeFixer)
2813       db.issue.audit('create', assignedtoMustBeFixer)
2815 So now, if an edit action attempts to set "assignedto" to a user that
2816 doesn't have the "Fixer" Permission, the error will be raised.
2819 Setting up a "wizard" (or "druid") for controlled adding of issues
2820 ------------------------------------------------------------------
2822 1. Set up the page templates you wish to use for data input. My wizard
2823    is going to be a two-step process: first figuring out what category
2824    of issue the user is submitting, and then getting details specific to
2825    that category. The first page includes a table of help, explaining
2826    what the category names mean, and then the core of the form::
2828     <form method="POST" onSubmit="return submit_once()"
2829           enctype="multipart/form-data">
2830       <input type="hidden" name="@template" value="add_page1">
2831       <input type="hidden" name="@action" value="page1_submit">
2833       <strong>Category:</strong>
2834       <tal:block tal:replace="structure context/category/menu" />
2835       <input type="submit" value="Continue">
2836     </form>
2838    The next page has the usual issue entry information, with the
2839    addition of the following form fragments::
2841     <form method="POST" onSubmit="return submit_once()"
2842           enctype="multipart/form-data"
2843           tal:condition="context/is_edit_ok"
2844           tal:define="cat request/form/category/value">
2846       <input type="hidden" name="@template" value="add_page2">
2847       <input type="hidden" name="@required" value="title">
2848       <input type="hidden" name="category" tal:attributes="value cat">
2849        .
2850        .
2851        .
2852     </form>
2854    Note that later in the form, I test the value of "cat" include form
2855    elements that are appropriate. For example::
2857     <tal:block tal:condition="python:cat in '6 10 13 14 15 16 17'.split()">
2858      <tr>
2859       <th>Operating System</th>
2860       <td tal:content="structure context/os/field"></td>
2861      </tr>
2862      <tr>
2863       <th>Web Browser</th>
2864       <td tal:content="structure context/browser/field"></td>
2865      </tr>
2866     </tal:block>
2868    ... the above section will only be displayed if the category is one
2869    of 6, 10, 13, 14, 15, 16 or 17.
2871 3. Determine what actions need to be taken between the pages - these are
2872    usually to validate user choices and determine what page is next. Now encode
2873    those actions in a new ``Action`` class and insert hooks to those actions in
2874    the "actions" attribute on on the ``interfaces.Client`` class, like so (see 
2875    `defining new web actions`_)::
2877     class Page1SubmitAction(Action):
2878         def handle(self):
2879             ''' Verify that the user has selected a category, and then move
2880                 on to page 2.
2881             '''
2882             category = self.form['category'].value
2883             if category == '-1':
2884                 self.error_message.append('You must select a category of report')
2885                 return
2886             # everything's ok, move on to the next page
2887             self.template = 'add_page2'
2889     actions = client.Client.actions + (
2890         ('page1_submit', Page1SubmitAction),
2891     )
2893 4. Use the usual "new" action as the ``@action`` on the final page, and
2894    you're done (the standard context/submit method can do this for you).
2897 Using an external password validation source
2898 --------------------------------------------
2900 We have a centrally-managed password changing system for our users. This
2901 results in a UN*X passwd-style file that we use for verification of
2902 users. Entries in the file consist of ``name:password`` where the
2903 password is encrypted using the standard UN*X ``crypt()`` function (see
2904 the ``crypt`` module in your Python distribution). An example entry
2905 would be::
2907     admin:aamrgyQfDFSHw
2909 Each user of Roundup must still have their information stored in the Roundup
2910 database - we just use the passwd file to check their password. To do this, we
2911 need to override the standard ``verifyPassword`` method defined in
2912 ``roundup.cgi.actions.LoginAction`` and register the new class with our
2913 ``Client`` class in the tracker home ``interfaces.py`` module::
2915     from roundup.cgi.actions import LoginAction    
2917     class ExternalPasswordLoginAction(LoginAction):
2918         def verifyPassword(self, userid, password):
2919             # get the user's username
2920             username = self.db.user.get(userid, 'username')
2922             # the passwords are stored in the "passwd.txt" file in the
2923             # tracker home
2924             file = os.path.join(self.db.config.TRACKER_HOME, 'passwd.txt')
2926             # see if we can find a match
2927             for ent in [line.strip().split(':') for line in
2928                                                 open(file).readlines()]:
2929                 if ent[0] == username:
2930                     return crypt.crypt(password, ent[1][:2]) == ent[1]
2932             # user doesn't exist in the file
2933             return 0
2935     class Client(client.Client):
2936         actions = client.Client.actions + (
2937             ('login', ExternalPasswordLoginAction)
2938         )
2940 What this does is look through the file, line by line, looking for a
2941 name that matches.
2943 We also remove the redundant password fields from the ``user.item``
2944 template.
2947 Adding a "vacation" flag to users for stopping nosy messages
2948 ------------------------------------------------------------
2950 When users go on vacation and set up vacation email bouncing, you'll
2951 start to see a lot of messages come back through Roundup "Fred is on
2952 vacation". Not very useful, and relatively easy to stop.
2954 1. add a "vacation" flag to your users::
2956          user = Class(db, "user",
2957                     username=String(),   password=Password(),
2958                     address=String(),    realname=String(),
2959                     phone=String(),      organisation=String(),
2960                     alternate_addresses=String(),
2961                     roles=String(), queries=Multilink("query"),
2962                     vacation=Boolean())
2964 2. So that users may edit the vacation flags, add something like the
2965    following to your ``user.item`` template::
2967      <tr>
2968       <th>On Vacation</th> 
2969       <td tal:content="structure context/vacation/field">vacation</td> 
2970      </tr> 
2972 3. edit your detector ``nosyreactor.py`` so that the ``nosyreaction()``
2973    consists of::
2975     def nosyreaction(db, cl, nodeid, oldvalues):
2976         users = db.user
2977         messages = db.msg
2978         # send a copy of all new messages to the nosy list
2979         for msgid in determineNewMessages(cl, nodeid, oldvalues):
2980             try:
2981                 # figure the recipient ids
2982                 sendto = []
2983                 seen_message = {}
2984                 recipients = messages.get(msgid, 'recipients')
2985                 for recipid in messages.get(msgid, 'recipients'):
2986                     seen_message[recipid] = 1
2988                 # figure the author's id, and indicate they've received
2989                 # the message
2990                 authid = messages.get(msgid, 'author')
2992                 # possibly send the message to the author, as long as
2993                 # they aren't anonymous
2994                 if (db.config.MESSAGES_TO_AUTHOR == 'yes' and
2995                         users.get(authid, 'username') != 'anonymous'):
2996                     sendto.append(authid)
2997                 seen_message[authid] = 1
2999                 # now figure the nosy people who weren't recipients
3000                 nosy = cl.get(nodeid, 'nosy')
3001                 for nosyid in nosy:
3002                     # Don't send nosy mail to the anonymous user (that
3003                     # user shouldn't appear in the nosy list, but just
3004                     # in case they do...)
3005                     if users.get(nosyid, 'username') == 'anonymous':
3006                         continue
3007                     # make sure they haven't seen the message already
3008                     if not seen_message.has_key(nosyid):
3009                         # send it to them
3010                         sendto.append(nosyid)
3011                         recipients.append(nosyid)
3013                 # generate a change note
3014                 if oldvalues:
3015                     note = cl.generateChangeNote(nodeid, oldvalues)
3016                 else:
3017                     note = cl.generateCreateNote(nodeid)
3019                 # we have new recipients
3020                 if sendto:
3021                     # filter out the people on vacation
3022                     sendto = [i for i in sendto 
3023                               if not users.get(i, 'vacation', 0)]
3025                     # map userids to addresses
3026                     sendto = [users.get(i, 'address') for i in sendto]
3028                     # update the message's recipients list
3029                     messages.set(msgid, recipients=recipients)
3031                     # send the message
3032                     cl.send_message(nodeid, msgid, note, sendto)
3033             except roundupdb.MessageSendError, message:
3034                 raise roundupdb.DetectorError, message
3036    Note that this is the standard nosy reaction code, with the small
3037    addition of::
3039     # filter out the people on vacation
3040     sendto = [i for i in sendto if not users.get(i, 'vacation', 0)]
3042    which filters out the users that have the vacation flag set to true.
3045 Adding a time log to your issues
3046 --------------------------------
3048 We want to log the dates and amount of time spent working on issues, and
3049 be able to give a summary of the total time spent on a particular issue.
3051 1. Add a new class to your tracker ``dbinit.py``::
3053     # storage for time logging
3054     timelog = Class(db, "timelog", period=Interval())
3056    Note that we automatically get the date of the time log entry
3057    creation through the standard property "creation".
3059 2. Link to the new class from your issue class (again, in
3060    ``dbinit.py``)::
3062     issue = IssueClass(db, "issue", 
3063                     assignedto=Link("user"), topic=Multilink("keyword"),
3064                     priority=Link("priority"), status=Link("status"),
3065                     times=Multilink("timelog"))
3067    the "times" property is the new link to the "timelog" class.
3069 3. We'll need to let people add in times to the issue, so in the web
3070    interface we'll have a new entry field. This is a special field
3071    because unlike the other fields in the issue.item template, it
3072    affects a different item (a timelog item) and not the template's
3073    item, an issue. We have a special syntax for form fields that affect
3074    items other than the template default item (see the cgi 
3075    documentation on `special form variables`_). In particular, we add a
3076    field to capture a new timelog item's perdiod::
3078     <tr> 
3079      <th>Time Log</th> 
3080      <td colspan=3><input type="text" name="timelog-1@period" /> 
3081       <br />(enter as '3y 1m 4d 2:40:02' or parts thereof) 
3082      </td> 
3083     </tr> 
3084          
3085    and another hidden field that links that new timelog item (new
3086    because it's marked as having id "-1") to the issue item. It looks
3087    like this::
3089      <input type="hidden" name="@link@times" value="timelog-1" />
3091    On submission, the "-1" timelog item will be created and assigned a
3092    real item id. The "times" property of the issue will have the new id
3093    added to it.
3095 4. We want to display a total of the time log times that have been
3096    accumulated for an issue. To do this, we'll need to actually write
3097    some Python code, since it's beyond the scope of PageTemplates to
3098    perform such calculations. We do this by adding a method to the
3099    TemplatingUtils class in our tracker ``interfaces.py`` module::
3101     class TemplatingUtils:
3102         ''' Methods implemented on this class will be available to HTML
3103             templates through the 'utils' variable.
3104         '''
3105         def totalTimeSpent(self, times):
3106             ''' Call me with a list of timelog items (which have an
3107                 Interval "period" property)
3108             '''
3109             total = Interval('0d')
3110             for time in times:
3111                 total += time.period._value
3112             return total
3114    Replace the ``pass`` line if one appears in your TemplatingUtils
3115    class. As indicated in the docstrings, we will be able to access the
3116    ``totalTimeSpent`` method via the ``utils`` variable in our templates.
3118 5. Display the time log for an issue::
3120      <table class="otherinfo" tal:condition="context/times">
3121       <tr><th colspan="3" class="header">Time Log
3122        <tal:block
3123             tal:replace="python:utils.totalTimeSpent(context.times)" />
3124       </th></tr>
3125       <tr><th>Date</th><th>Period</th><th>Logged By</th></tr>
3126       <tr tal:repeat="time context/times">
3127        <td tal:content="time/creation"></td>
3128        <td tal:content="time/period"></td>
3129        <td tal:content="time/creator"></td>
3130       </tr>
3131      </table>
3133    I put this just above the Messages log in my issue display. Note our
3134    use of the ``totalTimeSpent`` method which will total up the times
3135    for the issue and return a new Interval. That will be automatically
3136    displayed in the template as text like "+ 1y 2:40" (1 year, 2 hours
3137    and 40 minutes).
3139 8. If you're using a persistent web server - roundup-server or
3140    mod_python for example - then you'll need to restart that to pick up
3141    the code changes. When that's done, you'll be able to use the new
3142    time logging interface.
3144 Using a UN*X passwd file as the user database
3145 ---------------------------------------------
3147 On some systems the primary store of users is the UN*X passwd file. It
3148 holds information on users such as their username, real name, password
3149 and primary user group.
3151 Roundup can use this store as its primary source of user information,
3152 but it needs additional information too - email address(es), roundup
3153 Roles, vacation flags, roundup hyperdb item ids, etc. Also, "retired"
3154 users must still exist in the user database, unlike some passwd files in
3155 which the users are removed when they no longer have access to a system.
3157 To make use of the passwd file, we therefore synchronise between the two
3158 user stores. We also use the passwd file to validate the user logins, as
3159 described in the previous example, `using an external password
3160 validation source`_. We keep the users lists in sync using a fairly
3161 simple script that runs once a day, or several times an hour if more
3162 immediate access is needed. In short, it:
3164 1. parses the passwd file, finding usernames, passwords and real names,
3165 2. compares that list to the current roundup user list:
3167    a. entries no longer in the passwd file are *retired*
3168    b. entries with mismatching real names are *updated*
3169    c. entries only exist in the passwd file are *created*
3171 3. send an email to administrators to let them know what's been done.
3173 The retiring and updating are simple operations, requiring only a call
3174 to ``retire()`` or ``set()``. The creation operation requires more
3175 information though - the user's email address and their roundup Roles.
3176 We're going to assume that the user's email address is the same as their
3177 login name, so we just append the domain name to that. The Roles are
3178 determined using the passwd group identifier - mapping their UN*X group
3179 to an appropriate set of Roles.
3181 The script to perform all this, broken up into its main components, is
3182 as follows. Firstly, we import the necessary modules and open the
3183 tracker we're to work on::
3185     import sys, os, smtplib
3186     from roundup import instance, date
3188     # open the tracker
3189     tracker_home = sys.argv[1]
3190     tracker = instance.open(tracker_home)
3192 Next we read in the *passwd* file from the tracker home::
3194     # read in the users
3195     file = os.path.join(tracker_home, 'users.passwd')
3196     users = [x.strip().split(':') for x in open(file).readlines()]
3198 Handle special users (those to ignore in the file, and those who don't
3199 appear in the file)::
3201     # users to not keep ever, pre-load with the users I know aren't
3202     # "real" users
3203     ignore = ['ekmmon', 'bfast', 'csrmail']
3205     # users to keep - pre-load with the roundup-specific users
3206     keep = ['comment_pool', 'network_pool', 'admin', 'dev-team',
3207             'cs_pool', 'anonymous', 'system_pool', 'automated']
3209 Now we map the UN*X group numbers to the Roles that users should have::
3211     roles = {
3212      '501': 'User,Tech',  # tech
3213      '502': 'User',       # finance
3214      '503': 'User,CSR',   # customer service reps
3215      '504': 'User',       # sales
3216      '505': 'User',       # marketing
3217     }
3219 Now we do all the work. Note that the body of the script (where we have
3220 the tracker database open) is wrapped in a ``try`` / ``finally`` clause,
3221 so that we always close the database cleanly when we're finished. So, we
3222 now do all the work::
3224     # open the database
3225     db = tracker.open('admin')
3226     try:
3227         # store away messages to send to the tracker admins
3228         msg = []
3230         # loop over the users list read in from the passwd file
3231         for user,passw,uid,gid,real,home,shell in users:
3232             if user in ignore:
3233                 # this user shouldn't appear in our tracker
3234                 continue
3235             keep.append(user)
3236             try:
3237                 # see if the user exists in the tracker
3238                 uid = db.user.lookup(user)
3240                 # yes, they do - now check the real name for correctness
3241                 if real != db.user.get(uid, 'realname'):
3242                     db.user.set(uid, realname=real)
3243                     msg.append('FIX %s - %s'%(user, real))
3244             except KeyError:
3245                 # nope, the user doesn't exist
3246                 db.user.create(username=user, realname=real,
3247                     address='%s@ekit-inc.com'%user, roles=roles[gid])
3248                 msg.append('ADD %s - %s (%s)'%(user, real, roles[gid]))
3250         # now check that all the users in the tracker are also in our
3251         # "keep" list - retire those who aren't
3252         for uid in db.user.list():
3253             user = db.user.get(uid, 'username')
3254             if user not in keep:
3255                 db.user.retire(uid)
3256                 msg.append('RET %s'%user)
3258         # if we did work, then send email to the tracker admins
3259         if msg:
3260             # create the email
3261             msg = '''Subject: %s user database maintenance
3263             %s
3264             '''%(db.config.TRACKER_NAME, '\n'.join(msg))
3266             # send the email
3267             smtp = smtplib.SMTP(db.config.MAILHOST)
3268             addr = db.config.ADMIN_EMAIL
3269             smtp.sendmail(addr, addr, msg)
3271         # now we're done - commit the changes
3272         db.commit()
3273     finally:
3274         # always close the database cleanly
3275         db.close()
3277 And that's it!
3280 Using an LDAP database for user information
3281 -------------------------------------------
3283 A script that reads users from an LDAP store using
3284 http://python-ldap.sf.net/ and then compares the list to the users in the
3285 roundup user database would be pretty easy to write. You'd then have it run
3286 once an hour / day (or on demand if you can work that into your LDAP store
3287 workflow). See the example `Using a UN*X passwd file as the user database`_
3288 for more information about doing this.
3290 To authenticate off the LDAP store (rather than using the passwords in the
3291 roundup user database) you'd use the same python-ldap module inside an
3292 extension to the cgi interface. You'd do this by overriding the method called
3293 "verifyPassword" on the LoginAction class in your tracker's interfaces.py
3294 module (see `using an external password validation source`_). The method is
3295 implemented by default as::
3297     def verifyPassword(self, userid, password):
3298         ''' Verify the password that the user has supplied
3299         '''
3300         stored = self.db.user.get(self.userid, 'password')
3301         if password == stored:
3302             return 1
3303         if not password and not stored:
3304             return 1
3305         return 0
3307 So you could reimplement this as something like::
3309     def verifyPassword(self, userid, password):
3310         ''' Verify the password that the user has supplied
3311         '''
3312         # look up some unique LDAP information about the user
3313         username = self.db.user.get(self.userid, 'username')
3314         # now verify the password supplied against the LDAP store
3317 Enabling display of either message summaries or the entire messages
3318 -------------------------------------------------------------------
3320 This is pretty simple - all we need to do is copy the code from the
3321 example `displaying only message summaries in the issue display`_ into
3322 our template alongside the summary display, and then introduce a switch
3323 that shows either one or the other. We'll use a new form variable,
3324 ``@whole_messages`` to achieve this::
3326  <table class="messages" tal:condition="context/messages">
3327   <tal:block tal:condition="not:request/form/@whole_messages/value | python:0">
3328    <tr><th colspan="3" class="header">Messages</th>
3329        <th colspan="2" class="header">
3330          <a href="?@whole_messages=yes">show entire messages</a>
3331        </th>
3332    </tr>
3333    <tr tal:repeat="msg context/messages">
3334     <td><a tal:attributes="href string:msg${msg/id}"
3335            tal:content="string:msg${msg/id}"></a></td>
3336     <td tal:content="msg/author">author</td>
3337     <td class="date" tal:content="msg/date/pretty">date</td>
3338     <td tal:content="msg/summary">summary</td>
3339     <td>
3340      <a tal:attributes="href string:?@remove@messages=${msg/id}&@action=edit">remove</a>
3341     </td>
3342    </tr>
3343   </tal:block>
3345   <tal:block tal:condition="request/form/@whole_messages/value | python:0">
3346    <tr><th colspan="2" class="header">Messages</th>
3347        <th class="header">
3348          <a href="?@whole_messages=">show only summaries</a>
3349        </th>
3350    </tr>
3351    <tal:block tal:repeat="msg context/messages">
3352     <tr>
3353      <th tal:content="msg/author">author</th>
3354      <th class="date" tal:content="msg/date/pretty">date</th>
3355      <th style="text-align: right">
3356       (<a tal:attributes="href string:?@remove@messages=${msg/id}&@action=edit">remove</a>)
3357      </th>
3358     </tr>
3359     <tr><td colspan="3" tal:content="msg/content"></td></tr>
3360    </tal:block>
3361   </tal:block>
3362  </table>
3365 Blocking issues that depend on other issues
3366 -------------------------------------------
3368 We needed the ability to mark certain issues as "blockers" - that is,
3369 they can't be resolved until another issue (the blocker) they rely on is
3370 resolved. To achieve this:
3372 1. Create a new property on the issue Class,
3373    ``blockers=Multilink("issue")``. Edit your tracker's dbinit.py file.
3374    Where the "issue" class is defined, something like::
3376     issue = IssueClass(db, "issue", 
3377                     assignedto=Link("user"), topic=Multilink("keyword"),
3378                     priority=Link("priority"), status=Link("status"))
3380    add the blockers entry like so::
3382     issue = IssueClass(db, "issue", 
3383                     blockers=Multilink("issue"),
3384                     assignedto=Link("user"), topic=Multilink("keyword"),
3385                     priority=Link("priority"), status=Link("status"))
3387 2. Add the new "blockers" property to the issue.item edit page, using
3388    something like::
3390     <th>Waiting On</th>
3391     <td>
3392      <span tal:replace="structure python:context.blockers.field(showid=1,
3393                                   size=20)" />
3394      <span tal:replace="structure python:db.issue.classhelp('id,title')" />
3395      <span tal:condition="context/blockers"
3396            tal:repeat="blk context/blockers">
3397       <br>View: <a tal:attributes="href string:issue${blk/id}"
3398                    tal:content="blk/id"></a>
3399      </span>
3401    You'll need to fiddle with your item page layout to find an
3402    appropriate place to put it - I'll leave that fun part up to you.
3403    Just make sure it appears in the first table, possibly somewhere near
3404    the "superseders" field.
3406 3. Create a new detector module (attached) which enforces the rules:
3408    - issues may not be resolved if they have blockers
3409    - when a blocker is resolved, it's removed from issues it blocks
3411    The contents of the detector should be something like this::
3413     def blockresolution(db, cl, nodeid, newvalues):
3414         ''' If the issue has blockers, don't allow it to be resolved.
3415         '''
3416         if nodeid is None:
3417             blockers = []
3418         else:
3419             blockers = cl.get(nodeid, 'blockers')
3420         blockers = newvalues.get('blockers', blockers)
3422         # don't do anything if there's no blockers or the status hasn't
3423         # changed
3424         if not blockers or not newvalues.has_key('status'):
3425             return
3427         # get the resolved state ID
3428         resolved_id = db.status.lookup('resolved')
3430         # format the info
3431         u = db.config.TRACKER_WEB
3432         s = ', '.join(['<a href="%sissue%s">%s</a>'%(
3433                         u,id,id) for id in blockers])
3434         if len(blockers) == 1:
3435             s = 'issue %s is'%s
3436         else:
3437             s = 'issues %s are'%s
3439         # ok, see if we're trying to resolve
3440         if newvalues['status'] == resolved_id:
3441             raise ValueError, "This issue can't be resolved until %s resolved."%s
3443     def resolveblockers(db, cl, nodeid, newvalues):
3444         ''' When we resolve an issue that's a blocker, remove it from the
3445             blockers list of the issue(s) it blocks.
3446         '''
3447         if not newvalues.has_key('status'):
3448             return
3450         # get the resolved state ID
3451         resolved_id = db.status.lookup('resolved')
3453         # interesting?
3454         if newvalues['status'] != resolved_id:
3455             return
3457         # yes - find all the blocked issues, if any, and remove me from
3458         # their blockers list
3459         issues = cl.find(blockers=nodeid)
3460         for issueid in issues:
3461             blockers = cl.get(issueid, 'blockers')
3462             if nodeid in blockers:
3463                 blockers.remove(nodeid)
3464                 cl.set(issueid, blockers=blockers)
3467     def init(db):
3468         # might, in an obscure situation, happen in a create
3469         db.issue.audit('create', blockresolution)
3470         db.issue.audit('set', blockresolution)
3472         # can only happen on a set
3473         db.issue.react('set', resolveblockers)
3475    Put the above code in a file called "blockers.py" in your tracker's
3476    "detectors" directory.
3478 4. Finally, and this is an optional step, modify the tracker web page
3479    URLs so they filter out issues with any blockers. You do this by
3480    adding an additional filter on "blockers" for the value "-1". For
3481    example, the existing "Show All" link in the "page" template (in the
3482    tracker's "html" directory) looks like this::
3484      <a href="issue?:sort=-activity&:group=priority&:filter=status&:columns=id,activity,title,creator,assignedto,status&status=-1,1,2,3,4,5,6,7">Show All</a><br>
3486    modify it to add the "blockers" info to the URL (note, both the
3487    ":filter" *and* "blockers" values must be specified)::
3489      <a href="issue?:sort=-activity&:group=priority&:filter=status,blockers&blockers=-1&:columns=id,activity,title,creator,assignedto,status&status=-1,1,2,3,4,5,6,7">Show All</a><br>
3491 That's it. You should now be able to set blockers on your issues. Note
3492 that if you want to know whether an issue has any other issues dependent
3493 on it (i.e. it's in their blockers list) you can look at the journal
3494 history at the bottom of the issue page - look for a "link" event to
3495 another issue's "blockers" property.
3497 Add users to the nosy list based on the topic
3498 ---------------------------------------------
3500 We need the ability to automatically add users to the nosy list based
3501 on the occurence of a topic. Every user should be allowed to edit his
3502 own list of topics for which he wants to be added to the nosy list.
3504 Below will be showed that such a change can be performed with only
3505 minimal understanding of the roundup system, but with clever use
3506 of Copy and Paste.
3508 This requires three changes to the tracker: a change in the database to
3509 allow per-user recording of the lists of topics for which he wants to
3510 be put on the nosy list, a change in the user view allowing to edit
3511 this list of topics, and addition of an auditor which updates the nosy
3512 list when a topic is set.
3514 Adding the nosy topic list
3515 ~~~~~~~~~~~~~~~~~~~~~~~~~~
3517 The change in the database to make is that for any user there should be
3518 a list of topics for which he wants to be put on the nosy list. Adding
3519 a ``Multilink`` of ``keyword`` seem to fullfill this (note that within
3520 the code topics are called ``keywords``.) As such, all what has to be
3521 done is to add a new field to the definition of ``user`` within the
3522 file ``dbinit.py``.  We will call this new field ``nosy_keywords``, and
3523 the updated definition of user will be::
3525     user = Class(db, "user", 
3526                     username=String(),   password=Password(),
3527                     address=String(),    realname=String(), 
3528                     phone=String(),      organisation=String(),
3529                     alternate_addresses=String(),
3530                     queries=Multilink('query'), roles=String(),
3531                     timezone=String(),
3532                     nosy_keywords=Multilink('keyword'))
3533  
3534 Changing the user view to allow changing the nosy topic list
3535 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3537 We want any user to be able to change the list of topics for which
3538 he will by default be added to the nosy list. We choose to add this
3539 to the user view, as is generated by the file ``html/user.item.html``.
3540 We easily can
3541 see that the topic field in the issue view has very similar editting
3542 requirements as our nosy topics, both being a list of topics. As
3543 such, we search for Topics in ``issue.item.html``, and extract the
3544 associated parts from there. We add this to ``user.item.html`` at the 
3545 bottom of the list of viewed items (i.e. just below the 'Alternate
3546 E-mail addresses' in the classic template)::
3548  <tr>
3549   <th>Nosy Topics</th>
3550   <td>
3551   <span tal:replace="structure context/nosy_keywords/field" />
3552   <span tal:replace="structure python:db.keyword.classhelp(property='nosy_keywords')" />
3553   </td>
3554  </tr>
3555   
3557 Addition of an auditor to update the nosy list
3558 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3560 The more difficult part is the addition of the logic to actually
3561 at the users to the nosy list when it is required. 
3562 The choice is made to perform this action when the topics on an
3563 item are set, including when an item is created.
3564 Here we choose to start out with a copy of the 
3565 ``detectors/nosyreaction.py`` detector, which we copy to the file
3566 ``detectors/nosy_keyword_reaction.py``. 
3567 This looks like a good start as it also adds users
3568 to the nosy list. A look through the code reveals that the
3569 ``nosyreaction`` function actually is sending the e-mail, which
3570 we do not need. As such, we can change the init function to::
3572     def init(db):
3573         db.issue.audit('create', update_kw_nosy)
3574         db.issue.audit('set', update_kw_nosy)
3576 After that we rename the ``updatenosy`` function to ``update_kw_nosy``.
3577 The first two blocks of code in that function relate to settings
3578 ``current`` to a combination of the old and new nosy lists. This
3579 functionality is left in the new auditor. The following block of
3580 code, which in ``updatenosy`` handled adding the assignedto user(s)
3581 to the nosy list, should be replaced by a block of code to add the
3582 interested users to the nosy list. We choose here to loop over all
3583 new topics, than loop over all users,
3584 and assign the user to the nosy list when the topic in the user's
3585 nosy_keywords. The next part in ``updatenosy``, adding the author
3586 and/or recipients of a message to the nosy list, obviously is not
3587 relevant here and thus is deleted from the new auditor. The last
3588 part, copying the new nosy list to newvalues, does not have to be changed.
3589 This brings the following function::
3591     def update_kw_nosy(db, cl, nodeid, newvalues):
3592         '''Update the nosy list for changes to the topics
3593         '''
3594         # nodeid will be None if this is a new node
3595         current = {}
3596         if nodeid is None:
3597             ok = ('new', 'yes')
3598         else:
3599             ok = ('yes',)
3600             # old node, get the current values from the node if they haven't
3601             # changed
3602             if not newvalues.has_key('nosy'):
3603                 nosy = cl.get(nodeid, 'nosy')
3604                 for value in nosy:
3605                     if not current.has_key(value):
3606                         current[value] = 1
3608         # if the nosy list changed in this transaction, init from the new value
3609         if newvalues.has_key('nosy'):
3610             nosy = newvalues.get('nosy', [])
3611             for value in nosy:
3612                 if not db.hasnode('user', value):
3613                     continue
3614                 if not current.has_key(value):
3615                     current[value] = 1
3617         # add users with topic in nosy_keywords to the nosy list
3618         if newvalues.has_key('topic') and newvalues['topic'] is not None:
3619             topic_ids = newvalues['topic']
3620             for topic in topic_ids:
3621                 # loop over all users,
3622                 # and assign user to nosy when topic in nosy_keywords
3623                 for user_id in db.user.list():
3624                     nosy_kw = db.user.get(user_id, "nosy_keywords")
3625                     found = 0
3626                     for kw in nosy_kw:
3627                         if kw == topic:
3628                             found = 1
3629                     if found:
3630                         current[user_id] = 1
3632         # that's it, save off the new nosy list
3633         newvalues['nosy'] = current.keys()
3635 and these two function are the only ones needed in the file.
3637 TODO: update this example to use the find() Class method.
3639 Caveats
3640 ~~~~~~~
3642 A few problems with the design here can be noted:
3644 Multiple additions
3645     When a user, after automatic selection, is manually removed
3646     from the nosy list, he again is added to the nosy list when the
3647     topic list of the issue is updated. A better design might be
3648     to only check which topics are new compared to the old list
3649     of topics, and only add users when they have indicated
3650     interest on a new topic.
3652     The code could also be changed to only trigger on the create() event,
3653     rather than also on the set() event, thus only setting the nosy list
3654     when the issue is created.
3656 Scalability
3657     In the auditor there is a loop over all users. For a site with
3658     only few users this will pose no serious problem, however, with
3659     many users this will be a serious performance bottleneck.
3660     A way out will be to link from the topics to the users which
3661     selected these topics a nosy topics. This will eliminate the
3662     loop over all users.
3665 Adding action links to the index page
3666 -------------------------------------
3668 Add a column to the item.index.html template.
3670 Resolving the issue::
3672   <a tal:attributes="href
3673      string:issue${i/id}?:status=resolved&:action=edit">resolve</a>
3675 "Take" the issue::
3677   <a tal:attributes="href
3678      string:issue${i/id}?:assignedto=${request/user/id}&:action=edit">take</a>
3680 ... and so on
3682 Users may only edit their issues
3683 --------------------------------
3685 Users registering themselves are granted Provisional access - meaning they
3686 have access to edit the issues they submit, but not others. We create a new
3687 Role called "Provisional User" which is granted to newly-registered users,
3688 and has limited access. One of the Permissions they have is the new "Edit
3689 Own" on issues (regular users have "Edit".) We back up the permissions with
3690 an auditor.
3692 First up, we create the new Role and Permission structure in
3693 ``dbinit.py``::
3695     # New users not approved by the admin
3696     db.security.addRole(name='Provisional User',
3697         description='New user registered via web or email')
3698     p = db.security.addPermission(name='Edit Own', klass='issue',
3699         description='Can only edit own issues')
3700     db.security.addPermissionToRole('Provisional User', p)
3702     # Assign the access and edit Permissions for issue to new users now
3703     p = db.security.getPermission('View', 'issue')
3704     db.security.addPermissionToRole('Provisional User', p)
3705     p = db.security.getPermission('Edit', 'issue')
3706     db.security.addPermissionToRole('Provisional User', p)
3708     # and give the new users access to the web and email interface
3709     p = db.security.getPermission('Web Access')
3710     db.security.addPermissionToRole('Provisional User', p)
3711     p = db.security.getPermission('Email Access')
3712     db.security.addPermissionToRole('Provisional User', p)
3715 Then in the ``config.py`` we change the Role assigned to newly-registered
3716 users, replacing the existing ``'User'`` values::
3718     NEW_WEB_USER_ROLES = 'Provisional User'
3719     NEW_EMAIL_USER_ROLES = 'Provisional User'
3721 Finally we add a new *auditor* to the ``detectors`` directory called
3722 ``provisional_user_auditor.py``::
3724  def audit_provisionaluser(db, cl, nodeid, newvalues):
3725      ''' New users are only allowed to modify their own issues.
3726      '''
3727      if (db.getuid() != cl.get(nodeid, 'creator')
3728          and db.security.hasPermission('Edit Own', db.getuid(), cl.classname)):
3729          raise ValueError, ('You are only allowed to edit your own %s'
3730                             % cl.classname)
3732  def init(db):
3733      # fire before changes are made
3734      db.issue.audit('set', audit_provisionaluser)
3735      db.issue.audit('retire', audit_provisionaluser)
3736      db.issue.audit('restore', audit_provisionaluser)
3738 Note that some older trackers might also want to change the ``page.html``
3739 template as follows::
3741  <p class="classblock"
3742  -       tal:condition="python:request.user.username != 'anonymous'">
3743  +       tal:condition="python:request.user.hasPermission('View', 'user')">
3744      <b>Administration</b><br>
3745      <tal:block tal:condition="python:request.user.hasPermission('Edit', None)">
3746       <a href="home?:template=classlist">Class List</a><br>
3748 (note that the "-" indicates a removed line, and the "+" indicates an added
3749 line).
3752 Colouring the rows in the issue index according to priority
3753 -----------------------------------------------------------
3755 A simple ``tal:attributes`` statement will do the bulk of the work here. In
3756 the ``issue.index.html`` template, add to the ``<tr>`` that displays the
3757 actual rows of data::
3759    <tr tal:attributes="class string:priority-${i/priority/plain}">
3761 and then in your stylesheet (``style.css``) specify the colouring for the
3762 different priorities, like::
3764    tr.priority-critical td {
3765        background-color: red;
3766    }
3768    tr.priority-urgent td {
3769        background-color: orange;
3770    }
3772 and so on, with far less offensive colours :)
3774 Editing multiple items in an index view
3775 ---------------------------------------
3777 To edit the status of all items in the item index view, edit the
3778 ``issue.item.html``:
3780 1. add a form around the listing table, so at the top it reads::
3782     <form method="POST" tal:attributes="action request/classname">
3783      <table class="list">
3785    and at the bottom of that table::
3787      </table>
3788     </form
3790    making sure you match the ``</table>`` from the list table, not the
3791    navigation table or the subsequent form table.
3793 2. in the display for the issue property, change::
3795     <td tal:condition="request/show/status"
3796         tal:content="python:i.status.plain() or default">&nbsp;</td>
3798    to::
3800     <td tal:condition="request/show/status"
3801         tal:content="structure i/status/field">&nbsp;</td>
3803    this will result in an edit field for the status property.
3805 3. after the ``tal:block`` which lists the actual index items (marked by
3806    ``tal:repeat="i batch"``) add a new table row::
3808     <tr>
3809      <td tal:attributes="colspan python:len(request.columns)">
3810       <input type="submit" value=" Save Changes ">
3811       <input type="hidden" name="@action" value="edit">
3812       <tal:block replace="structure request/indexargs_form" />
3813      </td>
3814     </tr>
3816    which gives us a submit button, indicates that we are performing an edit
3817    on any changed statuses and the final block will make sure that the
3818    current index view parameters (filtering, columns, etc) will be used in 
3819    rendering the next page (the results of the editing).
3821 -------------------
3823 Back to `Table of Contents`_
3825 .. _`Table of Contents`: index.html
3826 .. _`design documentation`: design.html