Code

*** empty log message ***
[roundup.git] / doc / customizing.txt
1 ===================
2 Customising Roundup
3 ===================
5 :Version: $Revision: 1.66 $
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 five 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. `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 configuration
56 for the web and e-mail components of roundup's interfaces. As the name
57 suggests, this file is a Python module. This means that any valid python
58 expression may be used in the file. Mostly though, you'll be setting the
59 configuration variables to string values. Python string values must be quoted
60 with either single or double quotes::
62    'this is a string'
63    "this is also a string - use it when you have a 'single quote' in the value"
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 so::
69     'roundup-admin@%s'%MAIL_DOMAIN
71 this will create a string ``'roundup-admin@tracker.domain.example'`` if
72 MAIL_DOMAIN is set to ``'tracker.domain.example'``.
74 You'll also note some values are set to::
76    os.path.join(TRACKER_HOME, 'db')
78 or similar. This creates a new string which holds the path to the "db"
79 directory in the TRACKER_HOME directory. This is just a convenience so if the
80 TRACKER_HOME changes you don't have to edit multiple valoues.
82 The configuration variables available are:
84 **TRACKER_HOME** - ``os.path.split(__file__)[0]``
85  The tracker home directory. The above default code will automatically
86  determine the tracker home for you, so you can just leave it alone.
88 **MAILHOST** - ``'localhost'``
89  The SMTP mail host that roundup will use to send e-mail.
91 **MAIL_DOMAIN** - ``'tracker.domain.example'``
92  The domain name used for email addresses.
94 **DATABASE** - ``os.path.join(TRACKER_HOME, 'db')``
95  This is the directory that the database is going to be stored in. By default
96  it is in the tracker home.
98 **TEMPLATES** - ``os.path.join(TRACKER_HOME, 'html')``
99  This is the directory that the HTML templates reside in. By default they are
100  in the tracker home.
102 **TRACKER_NAME** - ``'Roundup issue tracker'``
103  A descriptive name for your roundup tracker. This is sent out in e-mails and
104  appears in the heading of CGI pages.
106 **TRACKER_EMAIL** - ``'issue_tracker@%s'%MAIL_DOMAIN``
107  The email address that e-mail sent to roundup should go to. Think of it as the
108  tracker's personal e-mail address.
110 **TRACKER_WEB** - ``'http://your.tracker.url.example/'``
111  The web address that the tracker is viewable at. This will be included in
112  information sent to users of the tracker.
114 **ADMIN_EMAIL** - ``'roundup-admin@%s'%MAIL_DOMAIN``
115  The email address that roundup will complain to if it runs into trouble.
117 **MESSAGES_TO_AUTHOR** - ``'yes'`` or``'no'``
118  Send nosy messages to the author of the message.
120 **ADD_AUTHOR_TO_NOSY** - ``'new'``, ``'yes'`` or ``'no'``
121  Does the author of a message get placed on the nosy list automatically?
122  If ``'new'`` is used, then the author will only be added when a message
123  creates a new issue. If ``'yes'``, then the author will be added on followups
124  too. If ``'no'``, they're never added to the nosy.
126 **ADD_RECIPIENTS_TO_NOSY** - ``'new'``, ``'yes'`` or ``'no'``
127  Do the recipients (To:, Cc:) of a message get placed on the nosy list?
128  If ``'new'`` is used, then the recipients will only be added when a message
129  creates a new issue. If ``'yes'``, then the recipients will be added on
130  followups too. If ``'no'``, they're never added to the nosy.
132 **EMAIL_SIGNATURE_POSITION** - ``'top'``, ``'bottom'`` or ``'none'``
133  Where to place the email signature in messages that Roundup generates.
135 **EMAIL_KEEP_QUOTED_TEXT** - ``'yes'`` or ``'no'``
136  Keep email citations. Citations are the part of e-mail which the sender has
137  quoted in their reply to previous e-mail.
139 **EMAIL_LEAVE_BODY_UNCHANGED** - ``'no'``
140  Preserve the email body as is. Enabiling this will cause the entire message
141  body to be stored, including all citations and signatures. It should be
142  either ``'yes'`` or ``'no'``.
144 **MAIL_DEFAULT_CLASS** - ``'issue'`` or ``''``
145  Default class to use in the mailgw if one isn't supplied in email
146  subjects. To disable, comment out the variable below or leave it blank.
148 The default config.py is given below - as you
149 can see, the MAIL_DOMAIN must be edited before any interaction with the
150 tracker is attempted.::
152     # roundup home is this package's directory
153     TRACKER_HOME=os.path.split(__file__)[0]
155     # The SMTP mail host that roundup will use to send mail
156     MAILHOST = 'localhost'
158     # The domain name used for email addresses.
159     MAIL_DOMAIN = 'your.tracker.email.domain.example'
161     # This is the directory that the database is going to be stored in
162     DATABASE = os.path.join(TRACKER_HOME, 'db')
164     # This is the directory that the HTML templates reside in
165     TEMPLATES = os.path.join(TRACKER_HOME, 'html')
167     # A descriptive name for your roundup tracker
168     TRACKER_NAME = 'Roundup issue tracker'
170     # The email address that mail to roundup should go to
171     TRACKER_EMAIL = 'issue_tracker@%s'%MAIL_DOMAIN
173     # The web address that the tracker is viewable at
174     TRACKER_WEB = 'http://your.tracker.url.example/'
176     # The email address that roundup will complain to if it runs into trouble
177     ADMIN_EMAIL = 'roundup-admin@%s'%MAIL_DOMAIN
179     # Send nosy messages to the author of the message
180     MESSAGES_TO_AUTHOR = 'no'           # either 'yes' or 'no'
182     # Does the author of a message get placed on the nosy list automatically?
183     # If 'new' is used, then the author will only be added when a message
184     # creates a new issue. If 'yes', then the author will be added on followups
185     # too. If 'no', they're never added to the nosy.
186     ADD_AUTHOR_TO_NOSY = 'new'          # one of 'yes', 'no', 'new'
188     # Do the recipients (To:, Cc:) of a message get placed on the nosy list?
189     # If 'new' is used, then the recipients will only be added when a message
190     # creates a new issue. If 'yes', then the recipients will be added on followups
191     # too. If 'no', they're never added to the nosy.
192     ADD_RECIPIENTS_TO_NOSY = 'new'      # either 'yes', 'no', 'new'
194     # Where to place the email signature
195     EMAIL_SIGNATURE_POSITION = 'bottom' # one of 'top', 'bottom', 'none'
197     # Keep email citations
198     EMAIL_KEEP_QUOTED_TEXT = 'no'       # either 'yes' or 'no'
200     # Preserve the email body as is
201     EMAIL_LEAVE_BODY_UNCHANGED = 'no'   # either 'yes' or 'no'
203     # Default class to use in the mailgw if one isn't supplied in email
204     # subjects. To disable, comment out the variable below or leave it blank.
205     # Examples:
206     MAIL_DEFAULT_CLASS = 'issue'   # use "issue" class by default
207     #MAIL_DEFAULT_CLASS = ''        # disable (or just comment the var out)
209 Tracker Schema
210 ==============
212 Note: if you modify the schema, you'll most likely need to edit the
213       `web interface`_ HTML template files and `detectors`_ to reflect
214       your changes.
216 A tracker schema defines what data is stored in the tracker's database.
217 Schemas are defined using Python code in the ``dbinit.py`` module of your
218 tracker. The "classic" schema looks like this::
220     pri = Class(db, "priority", name=String(), order=String())
221     pri.setkey("name")
223     stat = Class(db, "status", name=String(), order=String())
224     stat.setkey("name")
226     keyword = Class(db, "keyword", name=String())
227     keyword.setkey("name")
229     user = Class(db, "user", username=String(), organisation=String(),
230         password=String(), address=String(), realname=String(), phone=String())
231     user.setkey("username")
233     msg = FileClass(db, "msg", author=Link("user"), summary=String(),
234         date=Date(), recipients=Multilink("user"), files=Multilink("file"))
236     file = FileClass(db, "file", name=String(), type=String())
238     issue = IssueClass(db, "issue", topic=Multilink("keyword"),
239         status=Link("status"), assignedto=Link("user"),
240         priority=Link("priority"))
241     issue.setkey('title')
243 Classes and Properties - creating a new information store
244 ---------------------------------------------------------
246 In the tracker above, we've defined 7 classes of information:
248   priority
249       Defines the possible levels of urgency for issues.
251   status
252       Defines the possible states of processing the issue may be in.
254   keyword
255       Initially empty, will hold keywords useful for searching issues.
257   user
258       Initially holding the "admin" user, will eventually have an entry for all
259       users using roundup.
261   msg
262       Initially empty, will all e-mail messages sent to or generated by
263       roundup.
265   file
266       Initially empty, will all files attached to issues.
268   issue
269       Initially empty, this is where the issue information is stored.
271 We define the "priority" and "status" classes to allow two things: reduction in
272 the amount of information stored on the issue and more powerful, accurate
273 searching of issues by priority and status. By only requiring a link on the
274 issue (which is stored as a single number) we reduce the chance that someone
275 mis-types a priority or status - or simply makes a new one up.
277 Class and Items
278 ~~~~~~~~~~~~~~~
280 A Class defines a particular class (or type) of data that will be stored in the
281 database. A class comprises one or more properties, which given the information
282 about the class items.
283 The actual data entered into the database, using class.create() are called
284 items. They have a special immutable property called id. We sometimes refer to
285 this as the itemid.
287 Properties
288 ~~~~~~~~~~
290 A Class is comprised of one or more properties of the following types:
292 * String properties are for storing arbitrary-length strings.
293 * Password properties are for storing encoded arbitrary-length strings. The
294   default encoding is defined on the roundup.password.Password class.
295 * Date properties store date-and-time stamps. Their values are Timestamp
296   objects.
297 * Number properties store numeric values.
298 * Boolean properties store on/off, yes/no, true/false values.
299 * A Link property refers to a single other item selected from a specified
300   class. The class is part of the property; the value is an integer, the id
301   of the chosen item.
302 * A Multilink property refers to possibly many items in a specified class.
303   The value is a list of integers.
305 FileClass
306 ~~~~~~~~~
308 FileClasses save their "content" attribute off in a separate file from the rest
309 of the database. This reduces the number of large entries in the database,
310 which generally makes databases more efficient, and also allows us to use
311 command-line tools to operate on the files. They are stored in the files sub-
312 directory of the db directory in your tracker.
314 IssueClass
315 ~~~~~~~~~~
317 IssueClasses automatically include the "messages", "files", "nosy", and
318 "superseder" properties.
319 The messages and files properties list the links to the messages and files
320 related to the issue. The nosy property is a list of links to users who wish to
321 be informed of changes to the issue - they get "CC'ed" e-mails when messages
322 are sent to or generated by the issue. The nosy reactor (in the detectors
323 directory) handles this action. The superceder link indicates an issue which
324 has superceded this one.
325 They also have the dynamically generated "creation", "activity" and "creator"
326 properties.
327 The value of the "creation" property is the date when an item was created, and
328 the value of the "activity" property is the date when any property on the item
329 was last edited (equivalently, these are the dates on the first and last
330 records in the item's journal). The "creator" property holds a link to the user
331 that created the issue.
333 setkey(property)
334 ~~~~~~~~~~~~~~~~
336 Select a String property of the class to be the key property. The key property
337 muse be unique, and allows references to the items in the class by the content
338 of the key property. That is, we can refer to users by their username, e.g.
339 let's say that there's an issue in roundup, issue 23. There's also a user,
340 richard who happens to be user 2. To assign an issue to him, we could do either
341 of::
343      roundup-admin set issue assignedto=2
345 or::
347      roundup-admin set issue assignedto=richard
349 Note, the same thing can be done in the web and e-mail interfaces.
351 create(information)
352 ~~~~~~~~~~~~~~~~~~~
354 Create an item in the database. This is generally used to create items in the
355 "definitional" classes like "priority" and "status".
358 Examples of adding to your schema
359 ---------------------------------
361 TODO
364 Detectors - adding behaviour to your tracker
365 ============================================
366 .. _detectors:
368 Detectors are initialised every time you open your tracker database, so you're
369 free to add and remove them any time, even after the database is initliased
370 via the "roundup-admin initalise" command.
372 The detectors in your tracker fire before (*auditors*) and after (*reactors*)
373 changes to the contents of your database. They are Python modules that sit in
374 your tracker's ``detectors`` directory. You will have some installed by
375 default - have a look. You can write new detectors or modify the existing
376 ones. The existing detectors installed for you are:
378 **nosyreaction.py**
379   This provides the automatic nosy list maintenance and email sending. The nosy
380   reactor (``nosyreaction``) fires when new messages are added to issues.
381   The nosy auditor (``updatenosy``) fires when issues are changed and figures
382   what changes need to be made to the nosy list (like adding new authors etc)
383 **statusauditor.py**
384   This provides the ``chatty`` auditor which changes the issue status from
385   ``unread`` or ``closed`` to ``chatting`` if new messages appear. It also
386   provides the ``presetunread`` auditor which pre-sets the status to
387   ``unread`` on new items if the status isn't explicitly defined.
389 See the detectors section in the `design document`__ for details of the
390 interface for detectors.
392 __ design.html
394 Sample additional detectors that have been found useful will appear in the
395 ``detectors`` directory of the Roundup distribution:
397 **newissuecopy.py**
398   This detector sends an email to a team address whenever a new issue is
399   created. The address is hard-coded into the detector, so edit it before you
400   use it (look for the text 'team@team.host') or you'll get email errors!
402   The detector code::
404     from roundup import roundupdb
406     def newissuecopy(db, cl, nodeid, oldvalues):
407         ''' Copy a message about new issues to a team address.
408         '''
409         # so use all the messages in the create
410         change_note = cl.generateCreateNote(nodeid)
412         # send a copy to the nosy list
413         for msgid in cl.get(nodeid, 'messages'):
414             try:
415                 # note: last arg must be a list
416                 cl.send_message(nodeid, msgid, change_note, ['team@team.host'])
417             except roundupdb.MessageSendError, message:
418                 raise roundupdb.DetectorError, message
420     def init(db):
421         db.issue.react('create', newissuecopy)
424 Database Content
425 ================
427 Note: if you modify the content of definitional classes, you'll most likely
428        need to edit the tracker `detectors`_ to reflect your changes.
430 Customisation of the special "definitional" classes (eg. status, priority,
431 resolution, ...) may be done either before or after the tracker is
432 initialised. The actual method of doing so is completely different in each
433 case though, so be careful to use the right one.
435 **Changing content before tracker initialisation**
436     Edit the dbinit module in your tracker to alter the items created in using
437     the create() methods.
439 **Changing content after tracker initialisation**
440     As the "admin" user, click on the "class list" link in the web interface
441     to bring up a list of all database classes. Click on the name of the class
442     you wish to change the content of.
444     You may also use the roundup-admin interface's create, set and retire
445     methods to add, alter or remove items from the classes in question.
447 See "`adding a new field to the classic schema`_" for an example that requires
448 database content changes.
451 Access Controls
452 ===============
454 A set of Permissions are built in to the security module by default:
456 - Edit (everything)
457 - View (everything)
459 The default interfaces define:
461 - Web Registration
462 - Web Access
463 - Web Roles
464 - Email Registration
465 - Email Access
467 These are hooked into the default Roles:
469 - Admin (Edit everything, View everything, Web Roles)
470 - User (Web Access, Email Access)
471 - Anonymous (Web Registration, Email Registration)
473 And finally, the "admin" user gets the "Admin" Role, and the "anonymous" user
474 gets the "Anonymous" assigned when the database is initialised on installation.
475 The two default schemas then define:
477 - Edit issue, View issue (both)
478 - Edit file, View file (both)
479 - Edit msg, View msg (both)
480 - Edit support, View support (extended only)
482 and assign those Permissions to the "User" Role. Put together, these settings
483 appear in the ``open()`` function of the tracker ``dbinit.py`` (the following
484 is taken from the "minimal" template ``dbinit.py``)::
486     #
487     # SECURITY SETTINGS
488     #
489     # new permissions for this schema
490     for cl in ('user', ):
491         db.security.addPermission(name="Edit", klass=cl,
492             description="User is allowed to edit "+cl)
493         db.security.addPermission(name="View", klass=cl,
494             description="User is allowed to access "+cl)
496     # and give the regular users access to the web and email interface
497     p = db.security.getPermission('Web Access')
498     db.security.addPermissionToRole('User', p)
499     p = db.security.getPermission('Email Access')
500     db.security.addPermissionToRole('User', p)
502     # May users view other user information? Comment these lines out
503     # if you don't want them to
504     p = db.security.getPermission('View', 'user')
505     db.security.addPermissionToRole('User', p)
507     # Assign the appropriate permissions to the anonymous user's Anonymous
508     # Role. Choices here are:
509     # - Allow anonymous users to register through the web
510     p = db.security.getPermission('Web Registration')
511     db.security.addPermissionToRole('Anonymous', p)
512     # - Allow anonymous (new) users to register through the email gateway
513     p = db.security.getPermission('Email Registration')
514     db.security.addPermissionToRole('Anonymous', p)
517 New User Roles
518 --------------
520 New users are assigned the Roles defined in the config file as:
522 - NEW_WEB_USER_ROLES
523 - NEW_EMAIL_USER_ROLES
526 Changing Access Controls
527 ------------------------
529 You may alter the configuration variables to change the Role that new web or
530 email users get, for example to not give them access to the web interface if
531 they register through email. 
533 You may use the ``roundup-admin`` "``security``" command to display the
534 current Role and Permission configuration in your tracker.
536 Adding a new Permission
537 ~~~~~~~~~~~~~~~~~~~~~~~
539 When adding a new Permission, you will need to:
541 1. add it to your tracker's dbinit so it is created
542 2. enable it for the Roles that should have it (verify with
543    "``roundup-admin security``")
544 3. add it to the relevant HTML interface templates
545 4. add it to the appropriate xxxPermission methods on in your tracker
546    interfaces module
548 Example Scenarios
549 ~~~~~~~~~~~~~~~~~
551 **automatic registration of users in the e-mail gateway**
552  By giving the "anonymous" user the "Email Registration" Role, any
553  unidentified user will automatically be registered with the tracker (with
554  no password, so they won't be able to log in through the web until an admin
555  sets them a password). Note: this is the default behaviour in the tracker
556  templates that ship with Roundup.
558 **anonymous access through the e-mail gateway**
559  Give the "anonymous" user the "Email Access" and ("Edit", "issue") Roles
560  but not giving them the "Email Registration" Role. This means that when an
561  unknown user sends email into the tracker, they're automatically logged in
562  as "anonymous". Since they don't have the "Email Registration" Role, they
563  won't be automatically registered, but since "anonymous" has permission
564  to use the gateway, they'll still be able to submit issues. Note that the
565  Sender information - their email address - will not be available - they're
566  *anonymous*.
568 **only developers may be assigned issues**
569  Create a new Permission called "Fixer" for the "issue" class. Create a new
570  Role "Developer" which has that Permission, and assign that to the
571  appropriate users. Filter the list of users available in the assignedto
572  list to include only those users. Enforce the Permission with an auditor. See
573  the example `restricting the list of users that are assignable to a task`_.
575 **only managers may sign off issues as complete**
576  Create a new Permission called "Closer" for the "issue" class. Create a new
577  Role "Manager" which has that Permission, and assign that to the appropriate
578  users. In your web interface, only display the "resolved" issue state option
579  when the user has the "Closer" Permissions. Enforce the Permission with
580  an auditor. This is very similar to the previous example, except that the
581  web interface check would look like::
583    <option tal:condition="python:request.user.hasPermission('Closer')"
584            value="resolved">Resolved</option>
585  
586 **don't give users who register through email web access**
587  Create a new Role called "Email User" which has all the Permissions of the
588  normal "User" Role minus the "Web Access" Permission. This will allow users
589  to send in emails to the tracker, but not access the web interface.
591 **let some users edit the details of all users**
592  Create a new Role called "User Admin" which has the Permission for editing
593  users::
595     db.security.addRole(name='User Admin', description='Managing users')
596     p = db.security.getPermission('Edit', 'user')
597     db.security.addPermissionToRole('User Admin', p)
599  and assign the Role to the users who need the permission.
602 Web Interface
603 =============
605 .. contents::
606    :local:
607    :depth: 1
609 The web is provided by the roundup.cgi.client module and is used by
610 roundup.cgi, roundup-server and ZRoundup.
611 In all cases, we determine which tracker is being accessed
612 (the first part of the URL path inside the scope of the CGI handler) and pass
613 control on to the tracker interfaces.Client class - which uses the Client class
614 from roundup.cgi.client - which handles the rest of
615 the access through its main() method. This means that you can do pretty much
616 anything you want as a web interface to your tracker.
618 Repurcussions of changing the tracker schema
619 ---------------------------------------------
621 If you choose to change the `tracker schema`_ you will need to ensure the web
622 interface knows about it:
624 1. Index, item and search pages for the relevant classes may need to have
625    properties added or removed,
626 2. The "page" template may require links to be changed, as might the "home"
627    page's content arguments.
629 How requests are processed
630 --------------------------
632 The basic processing of a web request proceeds as follows:
634 1. figure out who we are, defaulting to the "anonymous" user
635 2. figure out what the request is for - we call this the "context"
636 3. handle any requested action (item edit, search, ...)
637 4. render the template requested by the context, resulting in HTML output
639 In some situations, exceptions occur:
641 - HTTP Redirect  (generally raised by an action)
642 - SendFile       (generally raised by determine_context)
643   here we serve up a FileClass "content" property
644 - SendStaticFile (generally raised by determine_context)
645   here we serve up a file from the tracker "html" directory
646 - Unauthorised   (generally raised by an action)
647   here the action is cancelled, the request is rendered and an error
648   message is displayed indicating that permission was not
649   granted for the action to take place
650 - NotFound       (raised wherever it needs to be)
651   this exception percolates up to the CGI interface that called the client
653 Determining web context
654 -----------------------
656 To determine the "context" of a request, we look at the URL and the special
657 request variable ``:template``. The URL path after the tracker identifier
658 is examined. Typical URL paths look like:
660 1.  ``/tracker/issue``
661 2.  ``/tracker/issue1``
662 3.  ``/tracker/_file/style.css``
663 4.  ``/cgi-bin/roundup.cgi/tracker/file1``
664 5.  ``/cgi-bin/roundup.cgi/tracker/file1/kitten.png``
666 where the "tracker identifier" is "tracker" in the above cases. That means
667 we're looking at "issue", "issue1", "_file/style.css", "file1" and
668 "file1/kitten.png" in the cases above. The path is generally only one
669 entry long - longer paths are handled differently.
671 a. if there is no path, then we are in the "home" context.
672 b. if the path starts with "_file" (as in example 3,
673    "/tracker/_file/style.css"), then the additional path entry,
674    "style.css" specifies the filename of a static file we're to serve up
675    from the tracker "html" directory. Raises a SendStaticFile
676    exception.
677 c. if there is something in the path (as in example 1, "issue"), it identifies
678    the tracker class we're to display.
679 d. if the path is an item designator (as in examples 2 and 4, "issue1" and
680    "file1"), then we're to display a specific item.
681 e. if the path starts with an item designator and is longer than
682    one entry (as in example 5, "file1/kitten.png"), then we're assumed
683    to be handling an item of a
684    FileClass, and the extra path information gives the filename
685    that the client is going to label the download with (ie
686    "file1/kitten.png" is nicer to download than "file1"). This
687    raises a SendFile exception.
689 Both b. and e. stop before we bother to
690 determine the template we're going to use. That's because they
691 don't actually use templates.
693 The template used is specified by the ``:template`` CGI variable,
694 which defaults to:
696 - only classname suplied:          "index"
697 - full item designator supplied:   "item"
700 Performing actions in web requests
701 ----------------------------------
703 When a user requests a web page, they may optionally also request for an
704 action to take place. As described in `how requests are processed`_, the
705 action is performed before the requested page is generated. Actions are
706 triggered by using a ``:action`` CGI variable, where the value is one of:
708 **login**
709  Attempt to log a user in.
711 **logout**
712  Log the user out - make them "anonymous".
714 **register**
715  Attempt to create a new user based on the contents of the form and then log
716  them in.
718 **edit**
719  Perform an edit of an item in the database. There are some special form
720  elements you may use:
722  :link=designator:property and :multilink=designator:property
723   The value specifies an item designator and the property on that
724   item to add *this* item to as a link or multilink.
725  :note
726   Create a message and attach it to the current item's
727   "messages" property.
728  :file
729   Create a file and attach it to the current item's
730   "files" property. Attach the file to the message created from
731   the :note if it's supplied.
732  :required=property,property,...
733   The named properties are required to be filled in the form.
734  :remove:<propname>=id(s)
735   The ids will be removed from the multilink property. You may have multiple
736   :remove:<propname> form elements for a single <propname>.
737  :add:<propname>=id(s)
738   The ids will be added to the multilink property. You may have multiple
739   :add:<propname> form elements for a single <propname>.
741 **new**
742  Add a new item to the database. You may use the same special form elements
743  as in the "edit" action.
745 **retire**
746  Retire the item in the database.
748 **editCSV**
749  Performs an edit of all of a class' items in one go. See also the
750  *class*.csv templating method which generates the CSV data to be edited, and
751  the "_generic.index" template which uses both of these features.
753 **search**
754  Mangle some of the form variables.
756  Set the form ":filter" variable based on the values of the
757  filter variables - if they're set to anything other than
758  "dontcare" then add them to :filter.
760  Also handle the ":queryname" variable and save off the query to
761  the user's query list.
763 Each of the actions is implemented by a corresponding *actionAction* (where
764 "action" is the name of the action) method on
765 the roundup.cgi.Client class, which also happens to be in your tracker as
766 interfaces.Client. So if you need to define new actions, you may add them
767 there (see `defining new web actions`_).
769 Each action also has a corresponding *actionPermission* (where
770 "action" is the name of the action) method which determines
771 whether the action is permissible given the current user. The base permission
772 checks are:
774 **login**
775  Determine whether the user has permission to log in.
776  Base behaviour is to check the user has "Web Access".
777 **logout**
778  No permission checks are made.
779 **register**
780  Determine whether the user has permission to register
781  Base behaviour is to check the user has "Web Registration".
782 **edit**
783  Determine whether the user has permission to edit this item.
784  Base behaviour is to check the user can edit this class. If we're
785  editing the "user" class, users are allowed to edit their own
786  details. Unless it's the "roles" property, which requires the
787  special Permission "Web Roles".
788 **new**
789  Determine whether the user has permission to create (edit) this item.
790  Base behaviour is to check the user can edit this class. No
791  additional property checks are made. Additionally, new user items
792  may be created if the user has the "Web Registration" Permission.
793 **editCSV**
794  Determine whether the user has permission to edit this class.
795  Base behaviour is to check the user can edit this class.
796 **search**
797  Determine whether the user has permission to search this class.
798  Base behaviour is to check the user can view this class.
801 Default templates
802 -----------------
804 Most customisation of the web view can be done by modifying the templates in
805 the tracker **html** directory. There are several types of files in there:
807 **page**
808   This template usually defines the overall look of your tracker. When you
809   view an issue, it appears inside this template. When you view an index, it
810   also appears inside this template. This template defines a macro called
811   "icing" which is used by almost all other templates as a coating for their
812   content, using its "content" slot. It will also define the "head_title"
813   and "body_title" slots to allow setting of the page title.
814 **home**
815   the default page displayed when no other page is indicated by the user
816 **home.classlist**
817   a special version of the default page that lists the classes in the tracker
818 **classname.item**
819   displays an item of the *classname* class
820 **classname.index**
821   displays a list of *classname* items
822 **classname.search**
823   displays a search page for *classname* items
824 **_generic.index**
825   used to display a list of items where there is no *classname*.index available
826 **_generic.help**
827   used to display a "class help" page where there is no *classname*.help
828 **user.register**
829   a special page just for the user class that renders the registration page
830 **style.css**
831   a static file that is served up as-is
833 Note: Remember that you can create any template extension you want to, so 
834 if you just want to play around with the templating for new issues, you can
835 copy the current "issue.item" template to "issue.test", and then access the
836 test template using the ":template" URL argument::
838    http://your.tracker.example/tracker/issue?:template=test
840 and it won't affect your users using the "issue.item" template.
843 How the templates work
844 ----------------------
846 Basic Templating Actions
847 ~~~~~~~~~~~~~~~~~~~~~~~~
849 Roundup's templates consist of special attributes on your template tags.
850 These attributes form the Template Attribute Language, or TAL. The basic tag
851 commands are:
853 **tal:define="variable expression; variable expression; ..."**
854    Define a new variable that is local to this tag and its contents. For
855    example::
857       <html tal:define="title request/description">
858        <head><title tal:content="title"></title></head>
859       </html>
861    In the example, the variable "title" is defined as being the result of the
862    expression "request/description". The tal:content command inside the <html>
863    tag may then use the "title" variable.
865 **tal:condition="expression"**
866    Only keep this tag and its contents if the expression is true. For example::
868      <p tal:condition="python:request.user.hasPermission('View', 'issue')">
869       Display some issue information.
870      </p>
872    In the example, the <p> tag and its contents are only displayed if the
873    user has the View permission for issues. We consider the number zero, a
874    blank string, an empty list, and the built-in variable nothing to be false
875    values. Nearly every other value is true, including non-zero numbers, and
876    strings with anything in them (even spaces!).
878 **tal:repeat="variable expression"**
879    Repeat this tag and its contents for each element of the sequence that the
880    expression returns, defining a new local variable and a special "repeat"
881    variable for each element. For example::
883      <tr tal:repeat="u user/list">
884       <td tal:content="u/id"></td>
885       <td tal:content="u/username"></td>
886       <td tal:content="u/realname"></td>
887      </tr>
889    The example would iterate over the sequence of users returned by
890    "user/list" and define the local variable "u" for each entry.
892 **tal:replace="expression"**
893    Replace this tag with the result of the expression. For example::
895     <span tal:replace="request/user/realname"></span>
897    The example would replace the <span> tag and its contents with the user's
898    realname. If the user's realname was "Bruce" then the resultant output
899    would be "Bruce".
901 **tal:content="expression"**
902    Replace the contents of this tag with the result of the expression. For
903    example::
905     <span tal:content="request/user/realname">user's name appears here</span>
907    The example would replace the contents of the <span> tag with the user's
908    realname. If the user's realname was "Bruce" then the resultant output
909    would be "<span>Bruce</span>".
911 **tal:attributes="attribute expression; attribute expression; ..."**
912    Set attributes on this tag to the results of expressions. For example::
914      <a tal:attributes="href string:user${request/user/id}">My Details</a>
916    In the example, the "href" attribute of the <a> tag is set to the value of
917    the "string:user${request/user/id}" expression, which will be something
918    like "user123".
920 **tal:omit-tag="expression"**
921    Remove this tag (but not its contents) if the expression is true. For
922    example::
924       <span tal:omit-tag="python:1">Hello, world!</span>
926    would result in output of::
928       Hello, world!
930 Note that the commands on a given tag are evaulated in the order above, so
931 *define* comes before *condition*, and so on.
933 Additionally, a tag is defined, tal:block, which is removed from output. Its
934 content is not, but the tag itself is (so don't go using any tal:attributes
935 commands on it). This is useful for making arbitrary blocks of HTML
936 conditional or repeatable (very handy for repeating multiple table rows,
937 which would othewise require an illegal tag placement to effect the repeat).
940 Templating Expressions
941 ~~~~~~~~~~~~~~~~~~~~~~
943 The expressions you may use in the attibute values may be one of the following
944 forms:
946 **Path Expressions** - eg. ``item/status/checklist``
947    These are object attribute / item accesses. Roughly speaking, the path
948    ``item/status/checklist`` is broken into parts ``item``, ``status``
949    and ``checklist``. The ``item`` part is the root of the expression.
950    We then look for a ``status`` attribute on ``item``, or failing that, a
951    ``status`` item (as in ``item['status']``). If that
952    fails, the path expression fails. When we get to the end, the object we're
953    left with is evaluated to get a string - methods are called, objects are
954    stringified. Path expressions may have an optional ``path:`` prefix, though
955    they are the default expression type, so it's not necessary.
957    If an expression evaluates to ``default`` then the expression is
958    "cancelled" - whatever HTML already exists in the template will remain
959    (tag content in the case of tal:content, attributes in the case of
960    tal:attributes).
962    If an expression evaluates to ``nothing`` then the target of the expression
963    is removed (tag content in the case of tal:content, attributes in the case
964    of tal:attributes and the tag itself in the case of tal:replace).
966    If an element in the path may not exist, then you can use the ``|``
967    operator in the expression to provide an alternative. So, the expression
968    ``request/form/foo/value | default`` would simply leave the current HTML
969    in place if the "foo" form variable doesn't exist.
971 **String Expressions** - eg. ``string:hello ${user/name}``
972    These expressions are simple string interpolations (though they can be just
973    plain strings with no interpolation if you want. The expression in the
974    ``${ ... }`` is just a path expression as above.
976 **Python Expressions** - eg. ``python: 1+1``
977    These expressions give the full power of Python. All the "root level"
978    variables are available, so ``python:item.status.checklist()`` would be
979    equivalent to ``item/status/checklist``, assuming that ``checklist`` is
980    a method.
982 Template Macros
983 ~~~~~~~~~~~~~~~
985 Macros are used in Roundup to save us from repeating the same common page
986 stuctures over and over. The most common (and probably only) macro you'll use
987 is the "icing" macro defined in the "page" template.
989 Macros are generated and used inside your templates using special attributes
990 similar to the `basic templating actions`_. In this case though, the
991 attributes belong to the Macro Expansion Template Attribute Language, or
992 METAL. The macro commands are:
994 **metal:define-macro="macro name"**
995   Define that the tag and its contents are now a macro that may be inserted
996   into other templates using the *use-macro* command. For example::
998     <html metal:define-macro="page">
999      ...
1000     </html>
1002   defines a macro called "page" using the ``<html>`` tag and its contents.
1003   Once defined, macros are stored on the template they're defined on in the
1004   ``macros`` attribute. You can access them later on through the ``templates``
1005   variable, eg. the most common ``templates/page/macros/icing`` to access the
1006   "page" macro of the "page" template.
1008 **metal:use-macro="path expression"**
1009   Use a macro, which is identified by the path expression (see above). This
1010   will replace the current tag with the identified macro contents. For
1011   example::
1013    <tal:block metal:use-macro="templates/page/macros/icing">
1014     ...
1015    </tal:block>
1017    will replace the tag and its contents with the "page" macro of the "page"
1018    template.
1020 **metal:define-slot="slot name"** and **metal:fill-slot="slot name"**
1021   To define *dynamic* parts of the macro, you define "slots" which may be 
1022   filled when the macro is used with a *use-macro* command. For example, the
1023   ``templates/page/macros/icing`` macro defines a slot like so::
1025     <title metal:define-slot="head_title">title goes here</title>
1027   In your *use-macro* command, you may now use a *fill-slot* command like
1028   this::
1030     <title metal:fill-slot="head_title">My Title</title>
1032   where the tag that fills the slot completely replaces the one defined as
1033   the slot in the macro.
1035 Note that you may not mix METAL and TAL commands on the same tag, but TAL
1036 commands may be used freely inside METAL-using tags (so your *fill-slots*
1037 tags may have all manner of TAL inside them).
1040 Information available to templates
1041 ----------------------------------
1043 Note: this is implemented by roundup.cgi.templating.RoundupPageTemplate
1045 The following variables are available to templates.
1047 **context**
1048   The current context. This is either None, a
1049   `hyperdb class wrapper`_ or a `hyperdb item wrapper`_
1050 **request**
1051   Includes information about the current request, including:
1052    - the current index information (``filterspec``, ``filter`` args,
1053      ``properties``, etc) parsed out of the form. 
1054    - methods for easy filterspec link generation
1055    - *user*, the current user item as an HTMLItem instance
1056    - *form*
1057      The current CGI form information as a mapping of form argument
1058      name to value
1059 **config**
1060   This variable holds all the values defined in the tracker config.py file 
1061   (eg. TRACKER_NAME, etc.)
1062 **db**
1063   The current database, used to access arbitrary database items.
1064 **templates**
1065   Access to all the tracker templates by name. Used mainly in *use-macro*
1066   commands.
1067 **utils**
1068   This variable makes available some utility functions like batching.
1069 **nothing**
1070   This is a special variable - if an expression evaluates to this, then the
1071   tag (in the case of a tal:replace), its contents (in the case of
1072   tal:content) or some attributes (in the case of tal:attributes) will not
1073   appear in the the output. So for example::
1075     <span tal:attributes="class nothing">Hello, World!</span>
1077   would result in::
1079     <span>Hello, World!</span>
1081 **default**
1082   Also a special variable - if an expression evaluates to this, then the
1083   existing HTML in the template will not be replaced or removed, it will
1084   remain. So::
1086     <span tal:replace="default">Hello, World!</span>
1088   would result in::
1090     <span>Hello, World!</span>
1092 The context variable
1093 ~~~~~~~~~~~~~~~~~~~~
1095 The *context* variable is one of three things based on the current context
1096 (see `determining web context`_ for how we figure this out):
1098 1. if we're looking at a "home" page, then it's None
1099 2. if we're looking at a specific hyperdb class, it's a
1100    `hyperdb class wrapper`_.
1101 3. if we're looking at a specific hyperdb item, it's a
1102    `hyperdb item wrapper`_.
1104 If the context is not None, we can access the properties of the class or item.
1105 The only real difference between cases 2 and 3 above are:
1107 1. the properties may have a real value behind them, and this will appear if
1108    the property is displayed through ``context/property`` or
1109    ``context/property/field``.
1110 2. the context's "id" property will be a false value in the second case, but
1111    a real, or true value in the third. Thus we can determine whether we're
1112    looking at a real item from the hyperdb by testing "context/id".
1114 Hyperdb class wrapper
1115 :::::::::::::::::::::
1117 Note: this is implemented by the roundup.cgi.templating.HTMLClass class.
1119 This wrapper object provides access to a hyperb class. It is used primarily
1120 in both index view and new item views, but it's also usable anywhere else that
1121 you wish to access information about a class, or the items of a class, when
1122 you don't have a specific item of that class in mind.
1124 We allow access to properties. There will be no "id" property. The value
1125 accessed through the property will be the current value of the same name from
1126 the CGI form.
1128 There are several methods available on these wrapper objects:
1130 =========== =============================================================
1131 Method      Description
1132 =========== =============================================================
1133 properties  return a `hyperdb property wrapper`_ for all of this class'
1134             properties.
1135 list        lists all of the active (not retired) items in the class.
1136 csv         return the items of this class as a chunk of CSV text.
1137 propnames   lists the names of the properties of this class.
1138 filter      lists of items from this class, filtered and sorted
1139             by the current *request* filterspec/filter/sort/group args
1140 classhelp   display a link to a javascript popup containing this class'
1141             "help" template.
1142 submit      generate a submit button (and action hidden element)
1143 renderWith  render this class with the given template.
1144 history     returns 'New node - no history' :)
1145 is_edit_ok  is the user allowed to Edit the current class?
1146 is_view_ok  is the user allowed to View the current class?
1147 =========== =============================================================
1149 Note that if you have a property of the same name as one of the above methods,
1150 you'll need to access it using a python "item access" expression. For example::
1152    python:context['list']
1154 will access the "list" property, rather than the list method.
1157 Hyperdb item wrapper
1158 ::::::::::::::::::::
1160 Note: this is implemented by the roundup.cgi.templating.HTMLItem class.
1162 This wrapper object provides access to a hyperb item.
1164 We allow access to properties. There will be no "id" property. The value
1165 accessed through the property will be the current value of the same name from
1166 the CGI form.
1168 There are several methods available on these wrapper objects:
1170 =============== =============================================================
1171 Method          Description
1172 =============== =============================================================
1173 submit          generate a submit button (and action hidden element)
1174 journal         return the journal of the current item (**not implemented**)
1175 history         render the journal of the current item as HTML
1176 renderQueryForm specific to the "query" class - render the search form for
1177                 the query
1178 hasPermission   specific to the "user" class - determine whether the user
1179                 has a Permission
1180 is_edit_ok      is the user allowed to Edit the current item?
1181 is_view_ok      is the user allowed to View the current item?
1182 =============== =============================================================
1185 Note that if you have a property of the same name as one of the above methods,
1186 you'll need to access it using a python "item access" expression. For example::
1188    python:context['journal']
1190 will access the "journal" property, rather than the journal method.
1193 Hyperdb property wrapper
1194 ::::::::::::::::::::::::
1196 Note: this is implemented by subclasses roundup.cgi.templating.HTMLProperty
1197 class (HTMLStringProperty, HTMLNumberProperty, and so on).
1199 This wrapper object provides access to a single property of a class. Its
1200 value may be either:
1202 1. if accessed through a `hyperdb item wrapper`_, then it's a value from the
1203    hyperdb
1204 2. if access through a `hyperdb class wrapper`_, then it's a value from the
1205    CGI form
1208 The property wrapper has some useful attributes:
1210 =============== =============================================================
1211 Attribute       Description
1212 =============== =============================================================
1213 _name           the name of the property
1214 _value          the value of the property if any - this is the actual value
1215                 retrieved from the hyperdb for this property
1216 =============== =============================================================
1218 There are several methods available on these wrapper objects:
1220 =========== =================================================================
1221 Method      Description
1222 =========== =================================================================
1223 plain       render a "plain" representation of the property
1224 field       render a form edit field for the property
1225 stext       only on String properties - render the value of the
1226             property as StructuredText (requires the StructureText module
1227             to be installed separately)
1228 multiline   only on String properties - render a multiline form edit
1229             field for the property
1230 email       only on String properties - render the value of the 
1231             property as an obscured email address
1232 confirm     only on Password properties - render a second form edit field for
1233             the property, used for confirmation that the user typed the
1234             password correctly. Generates a field with name "name:confirm".
1235 reldate     only on Date properties - render the interval between the
1236             date and now
1237 pretty      only on Interval properties - render the interval in a
1238             pretty format (eg. "yesterday")
1239 menu        only on Link and Multilink properties - render a form select
1240             list for this property
1241 reverse     only on Multilink properties - produce a list of the linked
1242             items in reverse order
1243 =========== =================================================================
1245 The request variable
1246 ~~~~~~~~~~~~~~~~~~~~
1248 Note: this is implemented by the roundup.cgi.templating.HTMLRequest class.
1250 The request variable is packed with information about the current request.
1252 .. taken from roundup.cgi.templating.HTMLRequest docstring
1254 =========== =================================================================
1255 Variable    Holds
1256 =========== =================================================================
1257 form        the CGI form as a cgi.FieldStorage
1258 env         the CGI environment variables
1259 base        the base URL for this tracker
1260 user        a HTMLUser instance for this user
1261 classname   the current classname (possibly None)
1262 template    the current template (suffix, also possibly None)
1263 form        the current CGI form variables in a FieldStorage
1264 =========== =================================================================
1266 **Index page specific variables (indexing arguments)**
1268 =========== =================================================================
1269 Variable    Holds
1270 =========== =================================================================
1271 columns     dictionary of the columns to display in an index page
1272 show        a convenience access to columns - request/show/colname will
1273             be true if the columns should be displayed, false otherwise
1274 sort        index sort column (direction, column name)
1275 group       index grouping property (direction, column name)
1276 filter      properties to filter the index on
1277 filterspec  values to filter the index on
1278 search_text text to perform a full-text search on for an index
1279 =========== =================================================================
1281 There are several methods available on the request variable:
1283 =============== =============================================================
1284 Method          Description
1285 =============== =============================================================
1286 description     render a description of the request - handle for the page
1287                 title
1288 indexargs_form  render the current index args as form elements
1289 indexargs_url   render the current index args as a URL
1290 base_javascript render some javascript that is used by other components of
1291                 the templating
1292 batch           run the current index args through a filter and return a
1293                 list of items (see `hyperdb item wrapper`_, and
1294                 `batching`_)
1295 =============== =============================================================
1297 The form variable
1298 :::::::::::::::::
1300 The form variable is a little special because it's actually a python
1301 FieldStorage object. That means that you have two ways to access its
1302 contents. For example, to look up the CGI form value for the variable
1303 "name", use the path expression::
1305    request/form/name/value
1307 or the python expression::
1309    python:request.form['name'].value
1311 Note the "item" access used in the python case, and also note the explicit
1312 "value" attribute we have to access. That's because the form variables are
1313 stored as MiniFieldStorages. If there's more than one "name" value in
1314 the form, then the above will break since ``request/form/name`` is actually a
1315 *list* of MiniFieldStorages. So it's best to know beforehand what you're
1316 dealing with.
1319 The db variable
1320 ~~~~~~~~~~~~~~~
1322 Note: this is implemented by the roundup.cgi.templating.HTMLDatabase class.
1324 Allows access to all hyperdb classes as attributes of this variable. If you
1325 want access to the "user" class, for example, you would use::
1327   db/user
1328   python:db.user
1330 The access results in a `hyperdb class wrapper`_.
1332 The templates variable
1333 ~~~~~~~~~~~~~~~~~~~~~~
1335 Note: this is implemented by the roundup.cgi.templating.Templates class.
1337 This variable doesn't have any useful methods defined. It supports being
1338 used in expressions to access the templates, and subsequently the template
1339 macros. You may access the templates using the following path expression::
1341    templates/name
1343 or the python expression::
1345    templates[name]
1347 where "name" is the name of the template you wish to access. The template you
1348 get access to has one useful attribute, "macros". To access a specific macro
1349 (called "macro_name"), use the path expression::
1351    templates/name/macros/macro_name
1353 or the python expression::
1355    templates[name].macros[macro_name]
1358 The utils variable
1359 ~~~~~~~~~~~~~~~~~~
1361 Note: this is implemented by the roundup.cgi.templating.TemplatingUtils class,
1362 but it may be extended as described below.
1364 =============== =============================================================
1365 Method          Description
1366 =============== =============================================================
1367 Batch           return a batch object using the supplied list
1368 =============== =============================================================
1370 You may add additional utility methods by writing them in your tracker
1371 ``interfaces.py`` module's ``TemplatingUtils`` class. See `adding a time log
1372 to your issues`_ for an example. The TemplatingUtils class itself will have a
1373 single attribute, ``client``, which may be used to access the ``client.db``
1374 when you need to perform arbitrary database queries.
1376 Batching
1377 ::::::::
1379 Use Batch to turn a list of items, or item ids of a given class, into a series
1380 of batches. Its usage is::
1382     python:util.Batch(sequence, size, start, end=0, orphan=0, overlap=0)
1384 or, to get the current index batch::
1386     request/batch
1388 The parameters are:
1390 ========= ==================================================================
1391 Parameter  Usage
1392 ========= ==================================================================
1393 sequence  a list of HTMLItems
1394 size      how big to make the sequence.
1395 start     where to start (0-indexed) in the sequence.
1396 end       where to end (0-indexed) in the sequence.
1397 orphan    if the next batch would contain less items than this
1398           value, then it is combined with this batch
1399 overlap   the number of items shared between adjacent batches
1400 ========= ==================================================================
1402 All of the parameters are assigned as attributes on the batch object. In
1403 addition, it has several more attributes:
1405 =============== ============================================================
1406 Attribute       Description
1407 =============== ============================================================
1408 start           indicates the start index of the batch. *Note: unlike the
1409                 argument, is a 1-based index (I know, lame)*
1410 first           indicates the start index of the batch *as a 0-based
1411                 index*
1412 length          the actual number of elements in the batch
1413 sequence_length the length of the original, unbatched, sequence.
1414 =============== ============================================================
1416 And several methods:
1418 =============== ============================================================
1419 Method          Description
1420 =============== ============================================================
1421 previous        returns a new Batch with the previous batch settings
1422 next            returns a new Batch with the next batch settings
1423 propchanged     detect if the named property changed on the current item
1424                 when compared to the last item
1425 =============== ============================================================
1427 An example of batching::
1429  <table class="otherinfo">
1430   <tr><th colspan="4" class="header">Existing Keywords</th></tr>
1431   <tr tal:define="keywords db/keyword/list"
1432       tal:repeat="start python:range(0, len(keywords), 4)">
1433    <td tal:define="batch python:utils.Batch(keywords, 4, start)"
1434        tal:repeat="keyword batch" tal:content="keyword/name">keyword here</td>
1435   </tr>
1436  </table>
1438 ... which will produce a table with four columns containing the items of the
1439 "keyword" class (well, their "name" anyway).
1441 Displaying Properties
1442 ---------------------
1444 Properties appear in the user interface in three contexts: in indices, in
1445 editors, and as search arguments.
1446 For each type of property, there are several display possibilities.
1447 For example, in an index view, a string property may just be
1448 printed as a plain string, but in an editor view, that property may be
1449 displayed in an editable field.
1452 Index Views
1453 -----------
1455 This is one of the class context views. It is also the default view for
1456 classes. The template used is "*classname*.index".
1458 Index View Specifiers
1459 ~~~~~~~~~~~~~~~~~~~~~
1461 An index view specifier (URL fragment) looks like this (whitespace has been
1462 added for clarity)::
1464      /issue?status=unread,in-progress,resolved&
1465             topic=security,ui&
1466             :group=+priority&
1467             :sort==activity&
1468             :filters=status,topic&
1469             :columns=title,status,fixer
1471 The index view is determined by two parts of the specifier: the layout part and
1472 the filter part. The layout part consists of the query parameters that begin
1473 with colons, and it determines the way that the properties of selected items
1474 are displayed. The filter part consists of all the other query parameters, and
1475 it determines the criteria by which items are selected for display.
1476 The filter part is interactively manipulated with the form widgets displayed in
1477 the filter section. The layout part is interactively manipulated by clicking on
1478 the column headings in the table.
1480 The filter part selects the union of the sets of items with values matching any
1481 specified Link properties and the intersection of the sets of items with values
1482 matching any specified Multilink properties.
1484 The example specifies an index of "issue" items. Only items with a "status" of
1485 either "unread" or "in-progres" or "resolved" are displayed, and only items
1486 with "topic" values including both "security" and "ui" are displayed. The items
1487 are grouped by priority, arranged in ascending order; and within groups, sorted
1488 by activity, arranged in descending order. The filter section shows filters for
1489 the "status" and "topic" properties, and the table includes columns for the
1490 "title", "status", and "fixer" properties.
1492 Searching Views
1493 ---------------
1495 Note: if you add a new column to the ``:columns`` form variable potentials
1496       then you will need to add the column to the appropriate `index views`_
1497       template so it is actually displayed.
1499 This is one of the class context views. The template used is typically
1500 "*classname*.search". The form on this page should have "search" as its
1501 ``:action`` variable. The "search" action:
1503 - sets up additional filtering, as well as performing indexed text searching
1504 - sets the ``:filter`` variable correctly
1505 - saves the query off if ``:query_name`` is set.
1507 The searching page should lay out any fields that you wish to allow the user
1508 to search one. If your schema contains a large number of properties, you
1509 should be wary of making all of those properties available for searching, as
1510 this can cause confusion. If the additional properties are Strings, consider
1511 having their value indexed, and then they will be searchable using the full
1512 text indexed search. This is both faster, and more useful for the end user.
1514 The two special form values on search pages which are handled by the "search"
1515 action are:
1517 :search_text
1518   Text to perform a search of the text index with. Results from that search
1519   will be used to limit the results of other filters (using an intersection
1520   operation)
1521 :query_name
1522   If supplied, the search parameters (including :search_text) will be saved
1523   off as a the query item and registered against the user's queries property.
1524   Note that the *classic* template schema has this ability, but the *minimal*
1525   template schema does not.
1528 Item Views
1529 ----------
1531 The basic view of a hyperdb item is provided by the "*classname*.item"
1532 template. It generally has three sections; an "editor", a "spool" and a
1533 "history" section.
1537 Editor Section
1538 ~~~~~~~~~~~~~~
1540 The editor section is used to manipulate the item - it may be a
1541 static display if the user doesn't have permission to edit the item.
1543 Here's an example of a basic editor template (this is the default "classic"
1544 template issue item edit form - from the "issue.item" template)::
1546  <table class="form">
1547  <tr>
1548   <th nowrap>Title</th>
1549   <td colspan=3 tal:content="structure python:context.title.field(size=60)">title</td>
1550  </tr>
1551  
1552  <tr>
1553   <th nowrap>Priority</th>
1554   <td tal:content="structure context/priority/menu">priority</td>
1555   <th nowrap>Status</th>
1556   <td tal:content="structure context/status/menu">status</td>
1557  </tr>
1558  
1559  <tr>
1560   <th nowrap>Superseder</th>
1561   <td>
1562    <span tal:replace="structure python:context.superseder.field(showid=1, size=20)" />
1563    <span tal:replace="structure python:db.issue.classhelp('id,title')" />
1564    <span tal:condition="context/superseder">
1565     <br>View: <span tal:replace="structure python:context.superseder.link(showid=1)" />
1566    </span>
1567   </td>
1568   <th nowrap>Nosy List</th>
1569   <td>
1570    <span tal:replace="structure context/nosy/field" />
1571    <span tal:replace="structure python:db.user.classhelp('username,realname,address,phone')" />
1572   </td>
1573  </tr>
1574  
1575  <tr>
1576   <th nowrap>Assigned To</th>
1577   <td tal:content="structure context/assignedto/menu">
1578    assignedto menu
1579   </td>
1580   <td>&nbsp;</td>
1581   <td>&nbsp;</td>
1582  </tr>
1583  
1584  <tr>
1585   <th nowrap>Change Note</th>
1586   <td colspan=3>
1587    <textarea name=":note" wrap="hard" rows="5" cols="60"></textarea>
1588   </td>
1589  </tr>
1590  
1591  <tr>
1592   <th nowrap>File</th>
1593   <td colspan=3><input type="file" name=":file" size="40"></td>
1594  </tr>
1595  
1596  <tr>
1597   <td>&nbsp;</td>
1598   <td colspan=3 tal:content="structure context/submit">
1599    submit button will go here
1600   </td>
1601  </tr>
1602  </table>
1605 When a change is submitted, the system automatically generates a message
1606 describing the changed properties. As shown in the example, the editor
1607 template can use the ":note" and ":file" fields, which are added to the
1608 standard change note message generated by Roundup.
1610 Spool Section
1611 ~~~~~~~~~~~~~
1613 The spool section lists related information like the messages and files of
1614 an issue.
1616 TODO
1619 History Section
1620 ~~~~~~~~~~~~~~~
1622 The final section displayed is the history of the item - its database journal.
1623 This is generally generated with the template::
1625  <tal:block tal:replace="structure context/history" />
1627 *To be done:*
1629 *The actual history entries of the item may be accessed for manual templating
1630 through the "journal" method of the item*::
1632  <tal:block tal:repeat="entry context/journal">
1633   a journal entry
1634  </tal:block>
1636 *where each journal entry is an HTMLJournalEntry.*
1638 Defining new web actions
1639 ------------------------
1641 You may define new actions to be triggered by the ``:action`` form variable.
1642 These are added to the tracker ``interfaces.py`` as methods on the ``Client``
1643 class. 
1645 Adding action methods takes three steps; first you `define the new action
1646 method`_, then you `register the action method`_ with the cgi interface so
1647 it may be triggered by the ``:action`` form variable. Finally you actually
1648 `use the new action`_ in your HTML form.
1650 See "`setting up a "wizard" (or "druid") for controlled adding of issues`_"
1651 for an example.
1653 Define the new action method
1654 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1656 The action methods have the following interface::
1658     def myActionMethod(self):
1659         ''' Perform some action. No return value is required.
1660         '''
1662 The *self* argument is an instance of your tracker ``instance.Client`` class - 
1663 thus it's mostly implemented by ``roundup.cgi.Client``. See the docstring of
1664 that class for details of what it can do.
1666 The method will typically check the ``self.form`` variable's contents. It
1667 may then:
1669 - add information to ``self.ok_message`` or ``self.error_message``
1670 - change the ``self.template`` variable to alter what the user will see next
1671 - raise Unauthorised, SendStaticFile, SendFile, NotFound or Redirect
1672   exceptions
1675 Register the action method
1676 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1678 The method is now written, but isn't available to the user until you add it to
1679 the `instance.Client`` class ``actions`` variable, like so::
1681     actions = client.Class.actions + (
1682         ('myaction', 'myActionMethod'),
1683     )
1685 This maps the action name "myaction" to the action method we defined.
1688 Use the new action
1689 ~~~~~~~~~~~~~~~~~~
1691 In your HTML form, add a hidden form element like so::
1693   <input type="hidden" name=":action" value="myaction">
1695 where "myaction" is the name you registered in the previous step.
1698 Examples
1699 ========
1701 .. contents::
1702    :local:
1703    :depth: 1
1705 Adding a new field to the classic schema
1706 ----------------------------------------
1708 This example shows how to add a new constrained property (ie. a selection of
1709 distinct values) to your tracker.
1711 Introduction
1712 ~~~~~~~~~~~~
1714 To make the classic schema of roundup useful as a todo tracking system
1715 for a group of systems administrators, it needed an extra data field
1716 per issue: a category.
1718 This would let sysads quickly list all todos in their particular
1719 area of interest without having to do complex queries, and without
1720 relying on the spelling capabilities of other sysads (a losing
1721 proposition at best).
1723 Adding a field to the database
1724 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1726 This is the easiest part of the change. The category would just be a plain
1727 string, nothing fancy. To change what is in the database you need to add
1728 some lines to the ``open()`` function in ``dbinit.py`` under the comment::
1730     # add any additional database schema configuration here
1732 add::
1734     category = Class(db, "category", name=String())
1735     category.setkey("name")
1737 Here we are setting up a chunk of the database which we are calling
1738 "category". It contains a string, which we are refering to as "name" for
1739 lack of a more imaginative title. Then we are setting the key of this chunk
1740 of the database to be that "name". This is equivalent to an index for
1741 database types. This also means that there can only be one category with a
1742 given name.
1744 Adding the above lines allows us to create categories, but they're not tied
1745 to the issues that we are going to be creating. It's just a list of categories
1746 off on its own, which isn't much use. We need to link it in with the issues.
1747 To do that, find the lines in the ``open()`` function in ``dbinit.py`` which
1748 set up the "issue" class, and then add a link to the category::
1750     issue = IssueClass(db, "issue", ... , category=Multilink("category"), ... )
1752 The Multilink() means that each issue can have many categories. If you were
1753 adding something with a more one to one relationship use Link() instead.
1755 That is all you need to do to change the schema. The rest of the effort is
1756 fiddling around so you can actually use the new category.
1758 Populating the new category class
1759 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1761 If you haven't initialised the database with the roundup-admin "initialise"
1762 command, then you can add the following to the tracker ``dbinit.py`` in the
1763 ``init()`` function under the comment::
1765     # add any additional database create steps here - but only if you
1766     # haven't initialised the database with the admin "initialise" command
1768 add::
1770      category = db.getclass('category')
1771      category.create(name="scipy", order="1")
1772      category.create(name="chaco", order="2")
1773      category.create(name="weave", order="3")
1775 If the database is initalised, the you need to use the roundup-admin tool::
1777      % roundup-admin -i <tracker home>
1778      Roundup <version> ready for input.
1779      Type "help" for help.
1780      roundup> create category name=scipy order=1
1781      1
1782      roundup> create category name=chaco order=1
1783      2
1784      roundup> create category name=weave order=1
1785      3
1786      roundup> exit...
1787      There are unsaved changes. Commit them (y/N)? y
1790 Setting up security on the new objects
1791 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1793 By default only the admin user can look at and change objects. This doesn't
1794 suit us, as we want any user to be able to create new categories as
1795 required, and obviously everyone needs to be able to view the categories of
1796 issues for it to be useful.
1798 We therefore need to change the security of the category objects. This is
1799 also done in the ``open()`` function of ``dbinit.py``.
1801 There are currently two loops which set up permissions and then assign them
1802 to various roles. Simply add the new "category" to both lists::
1804     # new permissions for this schema
1805     for cl in 'issue', 'file', 'msg', 'user', 'category':
1806         db.security.addPermission(name="Edit", klass=cl,
1807             description="User is allowed to edit "+cl)
1808         db.security.addPermission(name="View", klass=cl,
1809             description="User is allowed to access "+cl)
1811     # Assign the access and edit permissions for issue, file and message
1812     # to regular users now
1813     for cl in 'issue', 'file', 'msg', 'category':
1814         p = db.security.getPermission('View', cl)
1815         db.security.addPermissionToRole('User', p)
1816         p = db.security.getPermission('Edit', cl)
1817         db.security.addPermissionToRole('User', p)
1819 So you are in effect doing the following::
1821     db.security.addPermission(name="Edit", klass='category',
1822         description="User is allowed to edit "+'category')
1823     db.security.addPermission(name="View", klass='category',
1824         description="User is allowed to access "+'category')
1826 which is creating two permission types; that of editing and viewing
1827 "category" objects respectively. Then the following lines assign those new
1828 permissions to the "User" role, so that normal users can view and edit
1829 "category" objects::
1831     p = db.security.getPermission('View', 'category')
1832     db.security.addPermissionToRole('User', p)
1834     p = db.security.getPermission('Edit', 'category')
1835     db.security.addPermissionToRole('User', p)
1837 This is all the work that needs to be done for the database. It will store
1838 categories, and let users view and edit them. Now on to the interface
1839 stuff.
1841 Changing the web left hand frame
1842 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1844 We need to give the users the ability to create new categories, and the
1845 place to put the link to this functionality is in the left hand function
1846 bar, under the "Issues" area. The file that defines how this area looks is
1847 ``html/page``, which is what we are going to be editing next.
1849 If you look at this file you can see that it contains a lot of "classblock"
1850 sections which are chunks of HTML that will be included or excluded in the
1851 output depending on whether the condition in the classblock is met. Under
1852 the end of the classblock for issue is where we are going to add the
1853 category code::
1855   <p class="classblock"
1856      tal:condition="python:request.user.hasPermission('View', 'category')">
1857    <b>Categories</b><br>
1858    <a tal:condition="python:request.user.hasPermission('Edit', 'category')"
1859       href="category?:template=item">New Category<br></a>
1860   </p>
1862 The first two lines is the classblock definition, which sets up a condition
1863 that only users who have "View" permission to the "category" object will
1864 have this section included in their output. Next comes a plain "Categories"
1865 header in bold. Everyone who can view categories will get that.
1867 Next comes the link to the editing area of categories. This link will only
1868 appear if the condition is matched: that condition being that the user has
1869 "Edit" permissions for the "category" objects. If they do have permission
1870 then they will get a link to another page which will let the user add new
1871 categories.
1873 Note that if you have permission to view but not edit categories then all
1874 you will see is a "Categories" header with nothing underneath it. This is
1875 obviously not very good interface design, but will do for now. I just claim
1876 that it is so I can add more links in this section later on. However to fix
1877 the problem you could change the condition in the classblock statement, so
1878 that only users with "Edit" permission would see the "Categories" stuff.
1880 Setting up a page to edit categories
1881 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1883 We defined code in the previous section which let users with the
1884 appropriate permissions see a link to a page which would let them edit
1885 conditions. Now we have to write that page.
1887 The link was for the item template for the category object. This translates
1888 into the system looking for a file called ``category.item`` in the ``html``
1889 tracker directory. This is the file that we are going to write now.
1891 First we add an info tag in a comment which doesn't affect the outcome
1892 of the code at all but is useful for debugging. If you load a page in a
1893 browser and look at the page source, you can see which sections come
1894 from which files by looking for these comments::
1896     <!-- category.item -->
1898 Next we need to add in the METAL macro stuff so we get the normal page
1899 trappings::
1901  <tal:block metal:use-macro="templates/page/macros/icing">
1902   <title metal:fill-slot="head_title">Category editing</title>
1903   <td class="page-header-top" metal:fill-slot="body_title">
1904    <h2>Category editing</h2>
1905   </td>
1906   <td class="content" metal:fill-slot="content">
1908 Next we need to setup up a standard HTML form, which is the whole
1909 purpose of this file. We link to some handy javascript which sends the form
1910 through only once. This is to stop users hitting the send button
1911 multiple times when they are impatient and thus having the form sent
1912 multiple times::
1914     <form method="POST" onSubmit="return submit_once()"
1915           enctype="multipart/form-data">
1917 Next we define some code which sets up the minimum list of fields that we
1918 require the user to enter. There will be only one field, that of "name", so
1919 they user better put something in it otherwise the whole form is pointless::
1921     <input type="hidden" name=":required" value="name">
1923 To get everything to line up properly we will put everything in a table,
1924 and put a nice big header on it so the user has an idea what is happening::
1926     <table class="form">
1927      <tr><th class="header" colspan=2>Category</th></tr>
1929 Next we need the actual field that the user is going to enter the new
1930 category. The "context.name.field(size=60)" bit tells roundup to generate a
1931 normal HTML field of size 60, and the contents of that field will be the
1932 "name" variable of the current context (which is "category"). The upshot of
1933 this is that when the user types something in to the form, a new category
1934 will be created with that name::
1936     <tr>
1937      <th nowrap>Name</th>
1938      <td tal:content="structure python:context.name.field(size=60)">name</td>
1939     </tr>
1941 Then a submit button so that the user can submit the new category::
1943     <tr>
1944      <td>&nbsp;</td>
1945      <td colspan=3 tal:content="structure context/submit">
1946       submit button will go here
1947      </td>
1948     </tr>
1950 Finally we finish off the tags we used at the start to do the METAL stuff::
1952   </td>
1953  </tal:block>
1955 So putting it all together, and closing the table and form we get::
1957  <!-- category.item -->
1958  <tal:block metal:use-macro="templates/page/macros/icing">
1959   <title metal:fill-slot="head_title">Category editing</title>
1960   <td class="page-header-top" metal:fill-slot="body_title">
1961    <h2>Category editing</h2>
1962   </td>
1963   <td class="content" metal:fill-slot="content">
1964    <form method="POST" onSubmit="return submit_once()"
1965          enctype="multipart/form-data">
1967     <input type="hidden" name=":required" value="name">
1969     <table class="form">
1970      <tr><th class="header" colspan=2>Category</th></tr>
1972      <tr>
1973       <th nowrap>Name</th>
1974       <td tal:content="structure python:context.name.field(size=60)">name</td>
1975      </tr>
1977      <tr>
1978       <td>&nbsp;</td>
1979       <td colspan=3 tal:content="structure context/submit">
1980        submit button will go here
1981       </td>
1982      </tr>
1983     </table>
1984    </form>
1985   </td>
1986  </tal:block>
1988 This is quite a lot to just ask the user one simple question, but
1989 there is a lot of setup for basically one line (the form line) to do
1990 its work. To add another field to "category" would involve one more line
1991 (well maybe a few extra to get the formatting correct).
1993 Adding the category to the issue
1994 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1996 We now have the ability to create issues to our hearts content, but
1997 that is pointless unless we can assign categories to issues.  Just like
1998 the ``html/category.item`` file was used to define how to add a new
1999 category, the ``html/issue.item`` is used to define how a new issue is
2000 created.
2002 Just like ``category.issue`` this file defines a form which has a table to lay
2003 things out. It doesn't matter where in the table we add new stuff,
2004 it is entirely up to your sense of aesthetics::
2006    <th nowrap>Category</th>
2007    <td><span tal:replace="structure context/category/field" />
2008        <span tal:replace="structure db/category/classhelp" />
2009    </td>
2011 First we define a nice header so that the user knows what the next section
2012 is, then the middle line does what we are most interested in. This
2013 ``context/category/field`` gets replaced with a field which contains the
2014 category in the current context (the current context being the new issue).
2016 The classhelp lines generate a link (labelled "list") to a popup window
2017 which contains the list of currently known categories.
2019 Searching on categories
2020 ~~~~~~~~~~~~~~~~~~~~~~~
2022 We can add categories, and create issues with categories. The next obvious
2023 thing that we would like to be would be to search issues based on their
2024 category, so that any one working on the web server could look at all
2025 issues in the category "Web" for example.
2027 If you look in the html/page file and look for the "Search Issues" you will
2028 see that it looks something like ``<a href="issue?:template=search">Search
2029 Issues</a>`` which shows us that when you click on "Search Issues" it will
2030 be looking for a ``issue.search`` file to display. So that is indeed the file
2031 that we are going to change.
2033 If you look at this file it should be starting to seem familiar. It is a
2034 simple HTML form using a table to define structure. You can add the new
2035 category search code anywhere you like within that form::
2037     <tr>
2038      <th>Category:</th>
2039      <td>
2040       <select name="category">
2041        <option value="">don't care</option>
2042        <option value="">------------</option>
2043        <option tal:repeat="s db/category/list" tal:attributes="value s/name"
2044                tal:content="s/name">category to filter on</option>
2045       </select>
2046      </td>
2047      <td><input type="checkbox" name=":columns" value="category" checked></td>
2048      <td><input type="radio" name=":sort" value="category"></td>
2049      <td><input type="radio" name=":group" value="category"></td>
2050     </tr>
2052 Most of this is straightforward to anyone who knows HTML. It is just
2053 setting up a select list followed by a checkbox and a couple of radio
2054 buttons. 
2056 The ``tal:repeat`` part repeats the tag for every item in the "category"
2057 table and setting "s" to be each category in turn.
2059 The ``tal:attributes`` part is setting up the ``value=`` part of the option tag
2060 to be the name part of "s" which is the current category in the loop.
2062 The ``tal:content`` part is setting the contents of the option tag to be the
2063 name part of "s" again. For objects more complex than category, obviously
2064 you would put an id in the value, and the descriptive part in the content;
2065 but for category they are the same.
2067 Adding category to the default view
2068 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2070 We can now add categories, add issues with categories, and search issues
2071 based on categories. This is everything that we need to do, however there
2072 is some more icing that we would like. I think the category of an issue is
2073 important enough that it should be displayed by default when listing all
2074 the issues.
2076 Unfortunately, this is a bit less obvious than the previous steps. The code
2077 defining how the issues look is in ``html/issue.index``. This is a large table
2078 with a form down the bottom for redisplaying and so forth. 
2080 Firstly we need to add an appropriate header to the start of the table::
2082     <th tal:condition="request/show/category">Category</th>
2084 The condition part of this statement is so that if the user has selected
2085 not to see the Category column then they won't.
2087 The rest of the table is a loop which will go through every issue that
2088 matches the display criteria. The loop variable is "i" - which means that
2089 every issue gets assigned to "i" in turn.
2091 The new part of code to display the category will look like this::
2093     <td tal:condition="request/show/category" tal:content="i/category"></td>
2095 The condition is the same as above: only display the condition when the
2096 user hasn't asked for it to be hidden. The next part is to set the content
2097 of the cell to be the category part of "i" - the current issue.
2099 Finally we have to edit ``html/page`` again. This time to tell it that when the
2100 user clicks on "Unnasigned Issues" or "All Issues" that the category should
2101 be displayed. If you scroll down the page file, you can see the links with
2102 lots of options. The option that we are interested in is the ``:columns=`` one
2103 which tells roundup which fields of the issue to display. Simply add
2104 "category" to that list and it all should work.
2107 Adding in state transition control
2108 ----------------------------------
2110 Sometimes tracker admins want to control the states that users may move issues
2111 to.
2113 1. add a Multilink property to the status class::
2115      stat = Class(db, "status", ... , transitions=Multilink('status'), ...)
2117    and then edit the statuses already created either:
2119    a. through the web using the class list -> status class editor, or
2120    b. using the roundup-admin "set" command.
2122 2. add an auditor module ``checktransition.py`` in your tracker's
2123    ``detectors`` directory::
2125      def checktransition(db, cl, nodeid, newvalues):
2126          ''' Check that the desired transition is valid for the "status"
2127              property.
2128          '''
2129          if not newvalues.has_key('status'):
2130              return
2131          current = cl.get(nodeid, 'status')
2132          new = newvalues['status']
2133          if new == current:
2134              return
2135          ok = db.status.get(current, 'transitions')
2136          if new not in ok:
2137              raise ValueError, 'Status not allowed to move from "%s" to "%s"'%(
2138                  db.status.get(current, 'name'), db.status.get(new, 'name'))
2140      def init(db):
2141          db.issue.audit('set', checktransition)
2143 3. in the ``issue.item`` template, change the status editing bit from::
2145     <th nowrap>Status</th>
2146     <td tal:content="structure context/status/menu">status</td>
2148    to::
2150     <th nowrap>Status</th>
2151     <td>
2152      <select tal:condition="context/id" name="status">
2153       <tal:block tal:define="ok context/status/transitions"
2154                  tal:repeat="state db/status/list">
2155        <option tal:condition="python:state.id in ok"
2156                tal:attributes="value state/id;
2157                                selected python:state.id == context.status.id"
2158                tal:content="state/name"></option>
2159       </tal:block>
2160      </select>
2161      <tal:block tal:condition="not:context/id"
2162                 tal:replace="structure context/status/menu" />
2163     </td>
2165    which displays only the allowed status to transition to.
2168 Displaying only message summaries in the issue display
2169 ------------------------------------------------------
2171 Alter the issue.item template section for messages to::
2173  <table class="messages" tal:condition="context/messages">
2174   <tr><th colspan=5 class="header">Messages</th></tr>
2175   <tr tal:repeat="msg context/messages">
2176    <td><a tal:attributes="href string:msg${msg/id}"
2177           tal:content="string:msg${msg/id}"></a></td>
2178    <td tal:content="msg/author">author</td>
2179    <td nowrap tal:content="msg/date/pretty">date</td>
2180    <td tal:content="msg/summary">summary</td>
2181    <td>
2182     <a tal:attributes="href string:?:remove:messages=${msg/id}&:action=edit">remove</a>
2183    </td>
2184   </tr>
2185  </table>
2187 Restricting the list of users that are assignable to a task
2188 -----------------------------------------------------------
2190 1. In your tracker's "dbinit.py", create a new Role, say "Developer"::
2192      db.security.addRole(name='Developer', description='A developer')
2194 2. Just after that, create a new Permission, say "Fixer", specific to "issue"::
2196      p = db.security.addPermission(name='Fixer', klass='issue',
2197          description='User is allowed to be assigned to fix issues')
2199 3. Then assign the new Permission to your "Developer" Role::
2201      db.security.addPermissionToRole('Developer', p)
2203 4. In the issue item edit page ("html/issue.item" in your tracker dir), use
2204    the new Permission in restricting the "assignedto" list::
2206     <select name="assignedto">
2207      <option value="-1">- no selection -</option>
2208      <tal:block tal:repeat="user db/user/list">
2209      <option tal:condition="python:user.hasPermission('Fixer', context.classname)"
2210              tal:attributes="value user/id;
2211                              selected python:user.id == context.assignedto"
2212              tal:content="user/realname"></option>
2213      </tal:block>
2214     </select>
2216 For extra security, you may wish to set up an auditor to enforce the
2217 Permission requirement (install this as "assignedtoFixer.py" in your tracker
2218 "detectors" directory)::
2220   def assignedtoMustBeFixer(db, cl, nodeid, newvalues):
2221       ''' Ensure the assignedto value in newvalues is a used with the Fixer
2222           Permission
2223       '''
2224       if not newvalues.has_key('assignedto'):
2225           # don't care
2226           return
2227   
2228       # get the userid
2229       userid = newvalues['assignedto']
2230       if not db.security.hasPermission('Fixer', userid, cl.classname):
2231           raise ValueError, 'You do not have permission to edit %s'%cl.classname
2233   def init(db):
2234       db.issue.audit('set', assignedtoMustBeFixer)
2235       db.issue.audit('create', assignedtoMustBeFixer)
2237 So now, if the edit attempts to set the assignedto to a user that doesn't have
2238 the "Fixer" Permission, the error will be raised.
2241 Setting up a "wizard" (or "druid") for controlled adding of issues
2242 ------------------------------------------------------------------
2244 1. Set up the page templates you wish to use for data input. My wizard
2245    is going to be a two-step process, first figuring out what category of
2246    issue the user is submitting, and then getting details specific to that
2247    category. The first page includes a table of help, explaining what the
2248    category names mean, and then the core of the form::
2250     <form method="POST" onSubmit="return submit_once()"
2251           enctype="multipart/form-data">
2252       <input type="hidden" name=":template" value="add_page1">
2253       <input type="hidden" name=":action" value="page1submit">
2255       <strong>Category:</strong>
2256       <tal:block tal:replace="structure context/category/menu" />
2257       <input type="submit" value="Continue">
2258     </form>
2260    The next page has the usual issue entry information, with the addition of
2261    the following form fragments::
2263     <form method="POST" onSubmit="return submit_once()"
2264           enctype="multipart/form-data" tal:condition="context/is_edit_ok"
2265           tal:define="cat request/form/category/value">
2267       <input type="hidden" name=":template" value="add_page2">
2268       <input type="hidden" name=":required" value="title">
2269       <input type="hidden" name="category" tal:attributes="value cat">
2271        .
2272        .
2273        .
2274     </form>
2276    Note that later in the form, I test the value of "cat" include form
2277    elements that are appropriate. For example::
2279     <tal:block tal:condition="python:cat in '6 10 13 14 15 16 17'.split()">
2280      <tr>
2281       <th nowrap>Operating System</th>
2282       <td tal:content="structure context/os/field"></td>
2283      </tr>
2284      <tr>
2285       <th nowrap>Web Browser</th>
2286       <td tal:content="structure context/browser/field"></td>
2287      </tr>
2288     </tal:block>
2290    ... the above section will only be displayed if the category is one of 6,
2291    10, 13, 14, 15, 16 or 17.
2293 3. Determine what actions need to be taken between the pages - these are
2294    usually to validate user choices and determine what page is next. Now
2295    encode those actions in methods on the interfaces Client class and insert
2296    hooks to those actions in the "actions" attribute on that class, like so::
2298     actions = client.Client.actions + (
2299         ('page1_submit', 'page1SubmitAction'),
2300     )
2302     def page1SubmitAction(self):
2303         ''' Verify that the user has selected a category, and then move on
2304             to page 2.
2305         '''
2306         category = self.form['category'].value
2307         if category == '-1':
2308             self.error_message.append('You must select a category of report')
2309             return
2310         # everything's ok, move on to the next page
2311         self.template = 'add_page2'
2313 4. Use the usual "new" action as the :action on the final page, and you're
2314    done (the standard context/submit method can do this for you).
2317 Using an external password validation source
2318 --------------------------------------------
2320 We have a centrally-managed password changing system for our users. This
2321 results in a UN*X passwd-style file that we use for verification of users.
2322 Entries in the file consist of ``name:password`` where the password is
2323 encrypted using the standard UN*X ``crypt()`` function (see the ``crypt``
2324 module in your Python distribution). An example entry would be::
2326     admin:aamrgyQfDFSHw
2328 Each user of Roundup must still have their information stored in the Roundup
2329 database - we just use the passwd file to check their password. To do this, we
2330 add the following code to our ``Client`` class in the tracker home
2331 ``interfaces.py`` module::
2333     def verifyPassword(self, userid, password):
2334         # get the user's username
2335         username = self.db.user.get(userid, 'username')
2337         # the passwords are stored in the "passwd.txt" file in the tracker
2338         # home
2339         file = os.path.join(self.db.config.TRACKER_HOME, 'passwd.txt')
2341         # see if we can find a match
2342         for ent in [line.strip().split(':') for line in open(file).readlines()]:
2343             if ent[0] == username:
2344                 return crypt.crypt(password, ent[1][:2]) == ent[1]
2346         # user doesn't exist in the file
2347         return 0
2349 What this does is look through the file, line by line, looking for a name that
2350 matches.
2352 We also remove the redundant password fields from the ``user.item`` template.
2355 Adding a "vacation" flag to users for stopping nosy messages
2356 ------------------------------------------------------------
2358 When users go on vacation and set up vacation email bouncing, you'll start to
2359 see a lot of messages come back through Roundup "Fred is on vacation". Not
2360 very useful, and relatively easy to stop.
2362 1. add a "vacation" flag to your users::
2364          user = Class(db, "user",
2365                     username=String(),   password=Password(),
2366                     address=String(),    realname=String(),
2367                     phone=String(),      organisation=String(),
2368                     alternate_addresses=String(),
2369                     roles=String(), queries=Multilink("query"),
2370                     vacation=Boolean())
2372 2. edit your detector ``nosyreactor.py`` so that the ``nosyreaction()``
2373    consists of::
2375     def nosyreaction(db, cl, nodeid, oldvalues):
2376         # send a copy of all new messages to the nosy list
2377         for msgid in determineNewMessages(cl, nodeid, oldvalues):
2378             try:
2379                 users = db.user
2380                 messages = db.msg
2382                 # figure the recipient ids
2383                 sendto = []
2384                 r = {}
2385                 recipients = messages.get(msgid, 'recipients')
2386                 for recipid in messages.get(msgid, 'recipients'):
2387                     r[recipid] = 1
2389                 # figure the author's id, and indicate they've received the
2390                 # message
2391                 authid = messages.get(msgid, 'author')
2393                 # possibly send the message to the author, as long as they aren't
2394                 # anonymous
2395                 if (db.config.MESSAGES_TO_AUTHOR == 'yes' and
2396                         users.get(authid, 'username') != 'anonymous'):
2397                     sendto.append(authid)
2398                 r[authid] = 1
2400                 # now figure the nosy people who weren't recipients
2401                 nosy = cl.get(nodeid, 'nosy')
2402                 for nosyid in nosy:
2403                     # Don't send nosy mail to the anonymous user (that user
2404                     # shouldn't appear in the nosy list, but just in case they
2405                     # do...)
2406                     if users.get(nosyid, 'username') == 'anonymous':
2407                         continue
2408                     # make sure they haven't seen the message already
2409                     if not r.has_key(nosyid):
2410                         # send it to them
2411                         sendto.append(nosyid)
2412                         recipients.append(nosyid)
2414                 # generate a change note
2415                 if oldvalues:
2416                     note = cl.generateChangeNote(nodeid, oldvalues)
2417                 else:
2418                     note = cl.generateCreateNote(nodeid)
2420                 # we have new recipients
2421                 if sendto:
2422                     # filter out the people on vacation
2423                     sendto = [i for i in sendto if not users.get(i, 'vacation', 0)]
2425                     # map userids to addresses
2426                     sendto = [users.get(i, 'address') for i in sendto]
2428                     # update the message's recipients list
2429                     messages.set(msgid, recipients=recipients)
2431                     # send the message
2432                     cl.send_message(nodeid, msgid, note, sendto)
2433             except roundupdb.MessageSendError, message:
2434                 raise roundupdb.DetectorError, message
2436    Note that this is the standard nosy reaction code, with the small addition
2437    of::
2439     # filter out the people on vacation
2440     sendto = [i for i in sendto if not users.get(i, 'vacation', 0)]
2442    which filters out the users that have the vacation flag set to true.
2445 Adding a time log to your issues
2446 --------------------------------
2448 We want to log the dates and amount of time spent working on issues, and be
2449 able to give a summary of the total time spent on a particular issue.
2451 1. Add a new class to your tracker ``dbinit.py``::
2453     # storage for time logging
2454     timelog = Class(db, "timelog", period=Interval())
2456    Note that we automatically get the date of the time log entry creation
2457    through the standard property "creation".
2459 2. Link to the new class from your issue class (again, in ``dbinit.py``)::
2461     issue = IssueClass(db, "issue", 
2462                     assignedto=Link("user"), topic=Multilink("keyword"),
2463                     priority=Link("priority"), status=Link("status"),
2464                     times=Multilink("timelog"))
2466    the "times" property is the new link to the "timelog" class.
2468 3. We'll need to let people add in times to the issue, so in the web interface
2469    we'll have a new entry field, just below the change note box::
2471     <tr>
2472      <th nowrap>Time Log</th>
2473      <td colspan=3><input name=":timelog">
2474       (enter as "3y 1m 4d 2:40:02" or parts thereof)
2475      </td>
2476     </tr>
2478    Note that we've made up a new form variable, but since we place a colon ":"
2479    in front of it, it won't clash with any existing property variables. The
2480    names you *can't* use are ``:note``, ``:file``, ``:action``, ``:required``
2481    and ``:template``. These variables are described in the section
2482    `performing actions in web requests`_.
2484 4. We also need to handle this new field in the CGI interface - the way to
2485    do this is through implementing a new form action (see `Setting up a
2486    "wizard" (or "druid") for controlled adding of issues`_ for another example
2487    where we implemented a new CGI form action).
2489    In this case, we'll want our action to:
2491    1. create a new "timelog" entry,
2492    2. fake that the issue's "times" property has been edited, and then
2493    3. call the normal CGI edit action handler.
2495    The code to do this is::
2497     actions = client.Client.actions + (
2498         ('edit_with_timelog', 'timelogEditAction'),
2499     )
2501     def timelogEditAction(self):
2502         ''' Handle the creation of a new time log entry if necessary.
2504             If we create a new entry, fake up a CGI form value for the altered
2505             "times" property of the issue being edited.
2507             Punt to the regular edit action when we're done.
2508         '''
2509         # if there's a timelog value specified, create an entry
2510         if self.form.has_key(':timelog') and \
2511                 self.form[':timelog'].value.strip():
2512             period = Interval(self.form[':timelog'].value)
2513             # create it
2514             newid = self.db.timelog.create(period=period)
2516             # if we're editing an existing item, get the old timelog value
2517             if self.nodeid:
2518                 l = self.db.issue.get(self.nodeid, 'times')
2519                 l.append(newid)
2520             else:
2521                 l = [newid]
2523             # now make the fake CGI form values
2524             for entry in l:
2525                 self.form.list.append(MiniFieldStorage('times', entry))
2527         # punt to the normal edit action
2528         return self.editItemAction()
2530    you add this code to your Client class in your tracker's ``interfaces.py``
2531    file.
2533 5. You'll also need to modify your ``issue.item`` form submit action so it
2534    calls the time logging action we just created::
2536     <tr>
2537      <td>&nbsp;</td>
2538      <td colspan=3>
2539       <tal:block tal:condition="context/id">
2540         <input type="hidden" name=":action" value="edit_with_timelog">
2541         <input type="submit" name="submit" value="Submit Changes">
2542       </tal:block>
2543       <tal:block tal:condition="not:context/id">
2544         <input type="hidden" name=":action" value="new">
2545         <input type="submit" name="submit" value="Submit New Issue">
2546       </tal:block>
2547      </td>
2548     </tr>
2550    Note that the "context/submit" command usually handles all that for you -
2551    isn't it handy? The important change is setting the action to
2552    "edit_with_timelog" for edit operations (where the item exists)
2554 6. We want to display a total of the time log times that have been accumulated
2555    for an issue. To do this, we'll need to actually write some Python code,
2556    since it's beyond the scope of PageTemplates to perform such calculations.
2557    We do this by adding a method to the TemplatingUtils class in our tracker
2558    ``interfaces.py`` module::
2561     class TemplatingUtils:
2562         ''' Methods implemented on this class will be available to HTML
2563             templates through the 'utils' variable.
2564         '''
2565         def totalTimeSpent(self, times):
2566             ''' Call me with a list of timelog items (which have an Interval 
2567                 "period" property)
2568             '''
2569             total = Interval('')
2570             for time in times:
2571                 total += time.period._value
2572             return total
2574    As indicated in the docstrings, we will be able to access the
2575    ``totalTimeSpent`` method via the ``utils`` variable in our templates. See
2577 7. Display the time log for an issue::
2579      <table class="otherinfo" tal:condition="context/times">
2580       <tr><th colspan="3" class="header">Time Log
2581        <tal:block tal:replace="python:utils.totalTimeSpent(context.times)" />
2582       </th></tr>
2583       <tr><th>Date</th><th>Period</th><th>Logged By</th></tr>
2584       <tr tal:repeat="time context/times">
2585        <td tal:content="time/creation"></td>
2586        <td tal:content="time/period"></td>
2587        <td tal:content="time/creator"></td>
2588       </tr>
2589      </table>
2591    I put this just above the Messages log in my issue display. Note our use
2592    of the ``totalTimeSpent`` method which will total up the times for the
2593    issue and return a new Interval. That will be automatically displayed in
2594    the template as text like "+ 1y 2:40" (1 year, 2 hours and 40 minutes).
2596 8. If you're using a persistent web server - roundup-server or mod_python for
2597    example - then you'll need to restart that to pick up the code changes.
2598    When that's done, you'll be able to use the new time logging interface.
2600 Using a UN*X passwd file as the user database
2601 ---------------------------------------------
2603 On some systems the primary store of users is the UN*X passwd file. It holds
2604 information on users such as their username, real name, password and primary
2605 user group.
2607 Roundup can use this store as its primary source of user information, but it
2608 needs additional information too - email address(es), roundup Roles, vacation
2609 flags, roundup hyperdb item ids, etc. Also, "retired" users must still exist
2610 in the user database, unlike some passwd files in which the users are removed
2611 when they no longer have access to a system.
2613 To make use of the passwd file, we therefore synchronise between the two user
2614 stores. We also use the passwd file to validate the user logins, as described
2615 in the previous example, `using an external password validation source`_. We
2616 keep the users lists in sync using a fairly simple script that runs once a
2617 day, or several times an hour if more immediate access is needed. In short, it:
2619 1. parses the passwd file, finding usernames, passwords and real names,
2620 2. compares that list to the current roundup user list:
2622    a. entries no longer in the passwd file are *retired*
2623    b. entries with mismatching real names are *updated*
2624    c. entries only exist in the passwd file are *created*
2626 3. send an email to administrators to let them know what's been done.
2628 The retiring and updating are simple operations, requiring only a call to
2629 ``retire()`` or ``set()``. The creation operation requires more information
2630 though - the user's email address and their roundup Roles. We're going to
2631 assume that the user's email address is the same as their login name, so we
2632 just append the domain name to that. The Roles are determined using the
2633 passwd group identifier - mapping their UN*X group to an appropriate set of
2634 Roles.
2636 The script to perform all this, broken up into its main components, is as
2637 follows. Firstly, we import the necessary modules and open the tracker we're
2638 to work on::
2640     import sys, os, smtplib
2641     from roundup import instance, date
2643     # open the tracker
2644     tracker_home = sys.argv[1]
2645     tracker = instance.open(tracker_home)
2647 Next we read in the *passwd* file from the tracker home::
2649     # read in the users
2650     file = os.path.join(tracker_home, 'users.passwd')
2651     users = [x.strip().split(':') for x in open(file).readlines()]
2653 Handle special users (those to ignore in the file, and those who don't appear
2654 in the file)::
2656     # users to not keep ever, pre-load with the users I know aren't
2657     # "real" users
2658     ignore = ['ekmmon', 'bfast', 'csrmail']
2660     # users to keep - pre-load with the roundup-specific users
2661     keep = ['comment_pool', 'network_pool', 'admin', 'dev-team', 'cs_pool',
2662         'anonymous', 'system_pool', 'automated']
2664 Now we map the UN*X group numbers to the Roles that users should have::
2666     roles = {
2667      '501': 'User,Tech',  # tech
2668      '502': 'User',       # finance
2669      '503': 'User,CSR',   # customer service reps
2670      '504': 'User',       # sales
2671      '505': 'User',       # marketing
2672     }
2674 Now we do all the work. Note that the body of the script (where we have the
2675 tracker database open) is wrapped in a ``try`` / ``finally`` clause, so that
2676 we always close the database cleanly when we're finished. So, we now do all
2677 the work::
2679     # open the database
2680     db = tracker.open('admin')
2681     try:
2682         # store away messages to send to the tracker admins
2683         msg = []
2685         # loop over the users list read in from the passwd file
2686         for user,passw,uid,gid,real,home,shell in users:
2687             if user in ignore:
2688                 # this user shouldn't appear in our tracker
2689                 continue
2690             keep.append(user)
2691             try:
2692                 # see if the user exists in the tracker
2693                 uid = db.user.lookup(user)
2695                 # yes, they do - now check the real name for correctness
2696                 if real != db.user.get(uid, 'realname'):
2697                     db.user.set(uid, realname=real)
2698                     msg.append('FIX %s - %s'%(user, real))
2699             except KeyError:
2700                 # nope, the user doesn't exist
2701                 db.user.create(username=user, realname=real,
2702                     address='%s@ekit-inc.com'%user, roles=roles[gid])
2703                 msg.append('ADD %s - %s (%s)'%(user, real, roles[gid]))
2705         # now check that all the users in the tracker are also in our "keep"
2706         # list - retire those who aren't
2707         for uid in db.user.list():
2708             user = db.user.get(uid, 'username')
2709             if user not in keep:
2710                 db.user.retire(uid)
2711                 msg.append('RET %s'%user)
2713         # if we did work, then send email to the tracker admins
2714         if msg:
2715             # create the email
2716             msg = '''Subject: %s user database maintenance
2718             %s
2719             '''%(db.config.TRACKER_NAME, '\n'.join(msg))
2721             # send the email
2722             smtp = smtplib.SMTP(db.config.MAILHOST)
2723             addr = db.config.ADMIN_EMAIL
2724             smtp.sendmail(addr, addr, msg)
2726         # now we're done - commit the changes
2727         db.commit()
2728     finally:
2729         # always close the database cleanly
2730         db.close()
2732 And that's it!
2735 Enabling display of either message summaries or the entire messages
2736 -------------------------------------------------------------------
2738 This is pretty simple - all we need to do is copy the code from the example
2739 `displaying only message summaries in the issue display`_ into our template
2740 alongside the summary display, and then introduce a switch that shows either
2741 one or the other. We'll use a new form variable, ``:whole_messages`` to
2742 achieve this::
2744  <table class="messages" tal:condition="context/messages">
2745   <tal:block tal:condition="not:request/form/:whole_messages/value | python:0">
2746    <tr><th colspan=3 class="header">Messages</th>
2747        <th colspan=2 class="header">
2748          <a href="?:whole_messages=yes">show entire messages</a>
2749        </th>
2750    </tr>
2751    <tr tal:repeat="msg context/messages">
2752     <td><a tal:attributes="href string:msg${msg/id}"
2753            tal:content="string:msg${msg/id}"></a></td>
2754     <td tal:content="msg/author">author</td>
2755     <td nowrap tal:content="msg/date/pretty">date</td>
2756     <td tal:content="msg/summary">summary</td>
2757     <td>
2758      <a tal:attributes="href string:?:remove:messages=${msg/id}&:action=edit">remove</a>
2759     </td>
2760    </tr>
2761   </tal:block>
2763   <tal:block tal:condition="request/form/:whole_messages/value | python:0">
2764    <tr><th colspan=2 class="header">Messages</th>
2765        <th class="header"><a href="?:whole_messages=">show only summaries</a></th>
2766    </tr>
2767    <tal:block tal:repeat="msg context/messages">
2768     <tr>
2769      <th tal:content="msg/author">author</th>
2770      <th nowrap tal:content="msg/date/pretty">date</th>
2771      <th style="text-align: right">
2772       (<a tal:attributes="href string:?:remove:messages=${msg/id}&:action=edit">remove</a>)
2773      </th>
2774     </tr>
2775     <tr><td colspan=3 tal:content="msg/content"></td></tr>
2776    </tal:block>
2777   </tal:block>
2778  </table>
2781 -------------------
2783 Back to `Table of Contents`_
2785 .. _`Table of Contents`: index.html
2786 .. _`design documentation`: design.html