Code

bb85c1c8417c2c965ccdb7d47796c0a7f359c5b4
[roundup.git] / doc / customizing.txt
1 ===================
2 Customising Roundup
3 ===================
5 :Version: $Revision: 1.48 $
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 Customisation of Roundup can take one of five forms:
18 1. `tracker configuration`_ file changes
19 2. database, or `tracker schema`_ changes
20 3. "definition" class `database content`_ changes
21 4. behavioural changes, through detectors_
22 5. `access controls`_
24 The third case is special because it takes two distinctly different forms
25 depending upon whether the tracker has been initialised or not. The other two
26 may be done at any time, before or after tracker initialisation. Yes, this
27 includes adding or removing properties from classes.
30 Trackers in a Nutshell
31 ======================
33 Trackers have the following structure:
35 =================== ========================================================
36 Tracker File        Description
37 =================== ========================================================
38 config.py           Holds the basic `tracker configuration`_                 
39 dbinit.py           Holds the `tracker schema`_                              
40 interfaces.py       Defines the Web and E-Mail interfaces for the tracker    
41 select_db.py        Selects the database back-end for the tracker            
42 db/                 Holds the tracker's database                             
43 db/files/           Holds the tracker's upload files and messages            
44 detectors/          Auditors and reactors for this tracker                   
45 html/               Web interface templates, images and style sheets         
46 =================== ======================================================== 
48 Tracker Configuration
49 =====================
51 The config.py located in your tracker home contains the basic
52 configuration for the web and e-mail components of roundup's interfaces. This
53 file is a Python module. The configuration variables available are:
55 **TRACKER_HOME** - ``os.path.split(__file__)[0]``
56  The tracker home directory. The above default code will automatically
57  determine the tracker home for you.
59 **MAILHOST** - ``'localhost'``
60  The SMTP mail host that roundup will use to send e-mail.
62 **MAIL_DOMAIN** - ``'your.tracker.email.domain.example'``
63  The domain name used for email addresses.
65 **DATABASE** - ``os.path.join(TRACKER_HOME, 'db')``
66  This is the directory that the database is going to be stored in. By default
67  it is in the tracker home.
69 **TEMPLATES** - ``os.path.join(TRACKER_HOME, 'html')``
70  This is the directory that the HTML templates reside in. By default they are
71  in the tracker home.
73 **TRACKER_NAME** - ``'Roundup issue tracker'``
74  A descriptive name for your roundup tracker. This is sent out in e-mails and
75  appears in the heading of CGI pages.
77 **TRACKER_EMAIL** - ``'issue_tracker@%s'%MAIL_DOMAIN``
78  The email address that e-mail sent to roundup should go to. Think of it as the
79  tracker's personal e-mail address.
81 **TRACKER_WEB** - ``'http://your.tracker.url.example/'``
82  The web address that the tracker is viewable at. This will be included in
83  information sent to users of the tracker.
85 **ADMIN_EMAIL** - ``'roundup-admin@%s'%MAIL_DOMAIN``
86  The email address that roundup will complain to if it runs into trouble.
88 **MESSAGES_TO_AUTHOR** - ``'yes'`` or``'no'``
89  Send nosy messages to the author of the message.
91 **ADD_AUTHOR_TO_NOSY** - ``'new'``, ``'yes'`` or ``'no'``
92  Does the author of a message get placed on the nosy list automatically?
93  If ``'new'`` is used, then the author will only be added when a message
94  creates a new issue. If ``'yes'``, then the author will be added on followups
95  too. If ``'no'``, they're never added to the nosy.
97 **ADD_RECIPIENTS_TO_NOSY** - ``'new'``, ``'yes'`` or ``'no'``
98  Do the recipients (To:, Cc:) of a message get placed on the nosy list?
99  If ``'new'`` is used, then the recipients will only be added when a message
100  creates a new issue. If ``'yes'``, then the recipients will be added on
101  followups too. If ``'no'``, they're never added to the nosy.
103 **EMAIL_SIGNATURE_POSITION** - ``'top'``, ``'bottom'`` or ``'none'``
104  Where to place the email signature in messages that Roundup generates.
106 **EMAIL_KEEP_QUOTED_TEXT** - ``'yes'`` or ``'no'``
107  Keep email citations. Citations are the part of e-mail which the sender has
108  quoted in their reply to previous e-mail.
110 **EMAIL_LEAVE_BODY_UNCHANGED** - ``'no'``
111  Preserve the email body as is. Enabiling this will cause the entire message
112  body to be stored, including all citations and signatures. It should be
113  either ``'yes'`` or ``'no'``.
115 **MAIL_DEFAULT_CLASS** - ``'issue'`` or ``''``
116  Default class to use in the mailgw if one isn't supplied in email
117  subjects. To disable, comment out the variable below or leave it blank.
119 The default config.py is given below - as you
120 can see, the MAIL_DOMAIN must be edited before any interaction with the
121 tracker is attempted.::
123     # roundup home is this package's directory
124     TRACKER_HOME=os.path.split(__file__)[0]
126     # The SMTP mail host that roundup will use to send mail
127     MAILHOST = 'localhost'
129     # The domain name used for email addresses.
130     MAIL_DOMAIN = 'your.tracker.email.domain.example'
132     # This is the directory that the database is going to be stored in
133     DATABASE = os.path.join(TRACKER_HOME, 'db')
135     # This is the directory that the HTML templates reside in
136     TEMPLATES = os.path.join(TRACKER_HOME, 'html')
138     # A descriptive name for your roundup tracker
139     TRACKER_NAME = 'Roundup issue tracker'
141     # The email address that mail to roundup should go to
142     TRACKER_EMAIL = 'issue_tracker@%s'%MAIL_DOMAIN
144     # The web address that the tracker is viewable at
145     TRACKER_WEB = 'http://your.tracker.url.example/'
147     # The email address that roundup will complain to if it runs into trouble
148     ADMIN_EMAIL = 'roundup-admin@%s'%MAIL_DOMAIN
150     # Send nosy messages to the author of the message
151     MESSAGES_TO_AUTHOR = 'no'           # either 'yes' or 'no'
153     # Does the author of a message get placed on the nosy list automatically?
154     # If 'new' is used, then the author will only be added when a message
155     # creates a new issue. If 'yes', then the author will be added on followups
156     # too. If 'no', they're never added to the nosy.
157     ADD_AUTHOR_TO_NOSY = 'new'          # one of 'yes', 'no', 'new'
159     # Do the recipients (To:, Cc:) of a message get placed on the nosy list?
160     # If 'new' is used, then the recipients will only be added when a message
161     # creates a new issue. If 'yes', then the recipients will be added on followups
162     # too. If 'no', they're never added to the nosy.
163     ADD_RECIPIENTS_TO_NOSY = 'new'      # either 'yes', 'no', 'new'
165     # Where to place the email signature
166     EMAIL_SIGNATURE_POSITION = 'bottom' # one of 'top', 'bottom', 'none'
168     # Keep email citations
169     EMAIL_KEEP_QUOTED_TEXT = 'no'       # either 'yes' or 'no'
171     # Preserve the email body as is
172     EMAIL_LEAVE_BODY_UNCHANGED = 'no'   # either 'yes' or 'no'
174     # Default class to use in the mailgw if one isn't supplied in email
175     # subjects. To disable, comment out the variable below or leave it blank.
176     # Examples:
177     MAIL_DEFAULT_CLASS = 'issue'   # use "issue" class by default
178     #MAIL_DEFAULT_CLASS = ''        # disable (or just comment the var out)
180 Tracker Schema
181 ==============
183 Note: if you modify the schema, you'll most likely need to edit the
184       `web interface`_ HTML template files and `detectors`_ to reflect
185       your changes.
187 A tracker schema defines what data is stored in the tracker's database.
188 The schemas shipped with Roundup turn it into a typical software bug tracker
189 or help desk.
191 XXX make sure we ship the help desk
193 Schemas are defined using Python code in the ``dbinit.py`` module of your
194 tracker. The "classic" schema looks like this::
196     pri = Class(db, "priority", name=String(), order=String())
197     pri.setkey("name")
198     pri.create(name="critical", order="1")
199     pri.create(name="urgent", order="2")
200     pri.create(name="bug", order="3")
201     pri.create(name="feature", order="4")
202     pri.create(name="wish", order="5")
204     stat = Class(db, "status", name=String(), order=String())
205     stat.setkey("name")
206     stat.create(name="unread", order="1")
207     stat.create(name="deferred", order="2")
208     stat.create(name="chatting", order="3")
209     stat.create(name="need-eg", order="4")
210     stat.create(name="in-progress", order="5")
211     stat.create(name="testing", order="6")
212     stat.create(name="done-cbb", order="7")
213     stat.create(name="resolved", order="8")
215     keyword = Class(db, "keyword", name=String())
216     keyword.setkey("name")
218     user = Class(db, "user", username=String(), password=String(),
219         address=String(), realname=String(), phone=String(),
220         organisation=String())
221     user.setkey("username")
222     user.create(username="admin", password=adminpw,
223         address=config.ADMIN_EMAIL)
225     msg = FileClass(db, "msg", author=Link("user"), recipients=Multilink
226         ("user"), date=Date(), summary=String(), files=Multilink("file"))
228     file = FileClass(db, "file", name=String(), type=String())
230     issue = IssueClass(db, "issue", assignedto=Link("user"),
231         topic=Multilink("keyword"), priority=Link("priority"), status=Link
232         ("status"))
233     issue.setkey('title')
235 XXX security definitions
237 Classes and Properties - creating a new information store
238 ---------------------------------------------------------
240 In the tracker above, we've defined 7 classes of information:
242   priority
243       Defines the possible levels of urgency for issues.
245   status
246       Defines the possible states of processing the issue may be in.
248   keyword
249       Initially empty, will hold keywords useful for searching issues.
251   user
252       Initially holding the "admin" user, will eventually have an entry for all
253       users using roundup.
255   msg
256       Initially empty, will all e-mail messages sent to or generated by
257       roundup.
259   file
260       Initially empty, will all files attached to issues.
262   issue
263       Initially empty, this is where the issue information is stored.
265 We define the "priority" and "status" classes to allow two things: reduction in
266 the amount of information stored on the issue and more powerful, accurate
267 searching of issues by priority and status. By only requiring a link on the
268 issue (which is stored as a single number) we reduce the chance that someone
269 mis-types a priority or status - or simply makes a new one up.
271 Class and Items
272 ~~~~~~~~~~~~~~~
274 A Class defines a particular class (or type) of data that will be stored in the
275 database. A class comprises one or more properties, which given the information
276 about the class items.
277 The actual data entered into the database, using class.create() are called
278 items. They have a special immutable property called id. We sometimes refer to
279 this as the itemid.
281 Properties
282 ~~~~~~~~~~
284 A Class is comprised of one or more properties of the following types:
286 * String properties are for storing arbitrary-length strings.
287 * Password properties are for storing encoded arbitrary-length strings. The
288   default encoding is defined on the roundup.password.Password class.
289 * Date properties store date-and-time stamps. Their values are Timestamp
290   objects.
291 * Number properties store numeric values.
292 * Boolean properties store on/off, yes/no, true/false values.
293 * A Link property refers to a single other item selected from a specified
294   class. The class is part of the property; the value is an integer, the id
295   of the chosen item.
296 * A Multilink property refers to possibly many items in a specified class.
297   The value is a list of integers.
299 FileClass
300 ~~~~~~~~~
302 FileClasses save their "content" attribute off in a separate file from the rest
303 of the database. This reduces the number of large entries in the database,
304 which generally makes databases more efficient, and also allows us to use
305 command-line tools to operate on the files. They are stored in the files sub-
306 directory of the db directory in your tracker.
308 IssueClass
309 ~~~~~~~~~~
311 IssueClasses automatically include the "messages", "files", "nosy", and
312 "superseder" properties.
313 The messages and files properties list the links to the messages and files
314 related to the issue. The nosy property is a list of links to users who wish to
315 be informed of changes to the issue - they get "CC'ed" e-mails when messages
316 are sent to or generated by the issue. The nosy reactor (in the detectors
317 directory) handles this action. The superceder link indicates an issue which
318 has superceded this one.
319 They also have the dynamically generated "creation", "activity" and "creator"
320 properties.
321 The value of the "creation" property is the date when an item was created, and
322 the value of the "activity" property is the date when any property on the item
323 was last edited (equivalently, these are the dates on the first and last
324 records in the item's journal). The "creator" property holds a link to the user
325 that created the issue.
327 setkey(property)
328 ~~~~~~~~~~~~~~~~
330 Select a String property of the class to be the key property. The key property
331 muse be unique, and allows references to the items in the class by the content
332 of the key property. That is, we can refer to users by their username, e.g.
333 let's say that there's an issue in roundup, issue 23. There's also a user,
334 richard who happens to be user 2. To assign an issue to him, we could do either
335 of::
337      roundup-admin set issue assignedto=2
339 or::
341      roundup-admin set issue assignedto=richard
343 Note, the same thing can be done in the web and e-mail interfaces.
345 create(information)
346 ~~~~~~~~~~~~~~~~~~~
348 Create an item in the database. This is generally used to create items in the
349 "definitional" classes like "priority" and "status".
352 Examples of adding to your schema
353 ---------------------------------
355 TODO
358 Detectors - adding behaviour to your tracker
359 ============================================
360 .. _detectors:
362 Detectors are initialised every time you open your tracker database, so you're
363 free to add and remove them any time, even after the database is initliased
364 via the "roundup-admin initalise" command.
366 The detectors in your tracker fire before (*auditors*) and after (*reactors*)
367 changes to the contents of your database. They are Python modules that sit in
368 your tracker's ``detectors`` directory. You will have some installed by
369 default - have a look. You can write new detectors or modify the existing
370 ones. The existing detectors installed for you are:
372 **nosyreaction.py**
373   This provides the automatic nosy list maintenance and email sending. The nosy
374   reactor (``nosyreaction``) fires when new messages are added to issues.
375   The nosy auditor (``updatenosy``) fires when issues are changed and figures
376   what changes need to be made to the nosy list (like adding new authors etc)
377 **statusauditor.py**
378   This provides the ``chatty`` auditor which changes the issue status from
379   ``unread`` or ``closed`` to ``chatting`` if new messages appear. It also
380   provides the ``presetunread`` auditor which pre-sets the status to
381   ``unread`` on new items if the status isn't explicitly defined.
383 See the detectors section in the `design document`__ for details of the
384 interface for detectors.
386 __ design.html
388 Sample additional detectors that have been found useful will appear in the
389 ``detectors`` directory of the Roundup distribution:
391 **newissuecopy.py**
392   This detector sends an email to a team address whenever a new issue is
393   created. The address is hard-coded into the detector, so edit it before you
394   use it (look for the text 'team@team.host') or you'll get email errors!
396   The detector code::
398     from roundup import roundupdb
400     def newissuecopy(db, cl, nodeid, oldvalues):
401         ''' Copy a message about new issues to a team address.
402         '''
403         # so use all the messages in the create
404         change_note = cl.generateCreateNote(nodeid)
406         # send a copy to the nosy list
407         for msgid in cl.get(nodeid, 'messages'):
408             try:
409                 # note: last arg must be a list
410                 cl.send_message(nodeid, msgid, change_note, ['team@team.host'])
411             except roundupdb.MessageSendError, message:
412                 raise roundupdb.DetectorError, message
414     def init(db):
415         db.issue.react('create', newissuecopy)
418 Database Content
419 ================
421 Note: if you modify the content of definitional classes, you'll most likely
422        need to edit the tracker `detectors`_ to reflect your changes.
424 Customisation of the special "definitional" classes (eg. status, priority,
425 resolution, ...) may be done either before or after the tracker is
426 initialised. The actual method of doing so is completely different in each
427 case though, so be careful to use the right one.
429 **Changing content before tracker initialisation**
430     Edit the dbinit module in your tracker to alter the items created in using
431     the create() methods.
433 **Changing content after tracker initialisation**
434     Use the roundup-admin interface's create, set and retire methods to add,
435     alter or remove items from the classes in question.
437 XXX example
440 Web Interface
441 =============
443 .. contents::
444    :local:
445    :depth: 1
447 The web is provided by the roundup.cgi.client module and is used by
448 roundup.cgi, roundup-server and ZRoundup.
449 In all cases, we determine which tracker is being accessed
450 (the first part of the URL path inside the scope of the CGI handler) and pass
451 control on to the tracker interfaces.Client class - which uses the Client class
452 from roundup.cgi.client - which handles the rest of
453 the access through its main() method. This means that you can do pretty much
454 anything you want as a web interface to your tracker.
456 Repurcussions of changing the tracker schema
457 ---------------------------------------------
459 If you choose to change the `tracker schema`_ you will need to ensure the web
460 interface knows about it:
462 1. Index, item and search pages for the relevant classes may need to have
463    properties added or removed,
464 2. The "page" template may require links to be changed, as might the "home"
465    page's content arguments.
467 How requests are processed
468 --------------------------
470 The basic processing of a web request proceeds as follows:
472 1. figure out who we are, defaulting to the "anonymous" user
473 2. figure out what the request is for - we call this the "context"
474 3. handle any requested action (item edit, search, ...)
475 4. render the template requested by the context, resulting in HTML output
477 In some situations, exceptions occur:
479 - HTTP Redirect  (generally raised by an action)
480 - SendFile       (generally raised by determine_context)
481   here we serve up a FileClass "content" property
482 - SendStaticFile (generally raised by determine_context)
483   here we serve up a file from the tracker "html" directory
484 - Unauthorised   (generally raised by an action)
485   here the action is cancelled, the request is rendered and an error
486   message is displayed indicating that permission was not
487   granted for the action to take place
488 - NotFound       (raised wherever it needs to be)
489   this exception percolates up to the CGI interface that called the client
491 Determining web context
492 -----------------------
494 To determine the "context" of a request, we look at the URL and the special
495 request variable ``:template``. The URL path after the tracker identifier
496 is examined. Typical URL paths look like:
498 1.  ``/tracker/issue``
499 2.  ``/tracker/issue1``
500 3.  ``/tracker/_file/style.css``
501 4.  ``/cgi-bin/roundup.cgi/tracker/file1``
502 5.  ``/cgi-bin/roundup.cgi/tracker/file1/kitten.png``
504 where the "tracker identifier" is "tracker" in the above cases. That means
505 we're looking at "issue", "issue1", "_file/style.css", "file1" and
506 "file1/kitten.png" in the cases above. The path is generally only one
507 entry long - longer paths are handled differently.
509 a. if there is no path, then we are in the "home" context.
510 b. if the path starts with "_file" (as in example 3,
511    "/tracker/_file/style.css"), then the additional path entry,
512    "style.css" specifies the filename of a static file we're to serve up
513    from the tracker "html" directory. Raises a SendStaticFile
514    exception.
515 c. if there is something in the path (as in example 1, "issue"), it identifies
516    the tracker class we're to display.
517 d. if the path is an item designator (as in examples 2 and 4, "issue1" and
518    "file1"), then we're to display a specific item.
519 e. if the path starts with an item designator and is longer than
520    one entry (as in example 5, "file1/kitten.png"), then we're assumed
521    to be handling an item of a
522    FileClass, and the extra path information gives the filename
523    that the client is going to label the download with (ie
524    "file1/kitten.png" is nicer to download than "file1"). This
525    raises a SendFile exception.
527 Both b. and e. stop before we bother to
528 determine the template we're going to use. That's because they
529 don't actually use templates.
531 The template used is specified by the ``:template`` CGI variable,
532 which defaults to:
534 - only classname suplied:          "index"
535 - full item designator supplied:   "item"
538 Performing actions in web requests
539 ----------------------------------
541 When a user requests a web page, they may optionally also request for an
542 action to take place. As described in `how requests are processed`_, the
543 action is performed before the requested page is generated. Actions are
544 triggered by using a ``:action`` CGI variable, where the value is one of:
546 **login**
547  Attempt to log a user in.
548 **logout**
549  Log the user out - make them "anonymous".
550 **register**
551  Attempt to create a new user based on the contents of the form and then log
552  them in.
553 **edit**
554  Perform an edit of an item in the database. There are some special form
555  elements you may use:
557  :link=designator:property and :multilink=designator:property
558   The value specifies an item designator and the property on that
559   item to add _this_ item to as a link or multilink.
560  :note
561   Create a message and attach it to the current item's
562   "messages" property.
563  :file
564   Create a file and attach it to the current item's
565   "files" property. Attach the file to the message created from
566   the :note if it's supplied.
567  :required=property,property,...
568   The named properties are required to be filled in the form.
570 **new**
571  Add a new item to the database. You may use the same special form elements
572  as in the "edit" action.
574 **editCSV**
575  Performs an edit of all of a class' items in one go. See also the
576  *class*.csv templating method which generates the CSV data to be edited, and
577  the "_generic.index" template which uses both of these features.
579 **search**
580  Mangle some of the form variables.
582  Set the form ":filter" variable based on the values of the
583  filter variables - if they're set to anything other than
584  "dontcare" then add them to :filter.
586  Also handle the ":queryname" variable and save off the query to
587  the user's query list.
589 Each of the actions is implemented by a corresponding *actionAction* (where
590 "action" is the name of the action) method on
591 the roundup.cgi.Client class, which also happens to be in your tracker as
592 interfaces.Client. So if you need to define new actions, you may add them
593 there (see `defining new web actions`_).
595 Each action also has a corresponding *actionPermission* (where
596 "action" is the name of the action) method which determines
597 whether the action is permissible given the current user. The base permission
598 checks are:
600 **login**
601  Determine whether the user has permission to log in.
602  Base behaviour is to check the user has "Web Access".
603 **logout**
604  No permission checks are made.
605 **register**
606  Determine whether the user has permission to register
607  Base behaviour is to check the user has "Web Registration".
608 **edit**
609  Determine whether the user has permission to edit this item.
610  Base behaviour is to check the user can edit this class. If we're
611  editing the "user" class, users are allowed to edit their own
612  details. Unless it's the "roles" property, which requires the
613  special Permission "Web Roles".
614 **new**
615  Determine whether the user has permission to create (edit) this item.
616  Base behaviour is to check the user can edit this class. No
617  additional property checks are made. Additionally, new user items
618  may be created if the user has the "Web Registration" Permission.
619 **editCSV**
620  Determine whether the user has permission to edit this class.
621  Base behaviour is to check the user can edit this class.
622 **search**
623  Determine whether the user has permission to search this class.
624  Base behaviour is to check the user can view this class.
627 Default templates
628 -----------------
630 Most customisation of the web view can be done by modifying the templates in
631 the tracker **html** directory. There are several types of files in there:
633 **page**
634   This template usually defines the overall look of your tracker. When you
635   view an issue, it appears inside this template. When you view an index, it
636   also appears inside this template. This template defines a macro called
637   "icing" which is used by almost all other templates as a coating for their
638   content, using its "content" slot. It will also define the "head_title"
639   and "body_title" slots to allow setting of the page title.
640 **home**
641   the default page displayed when no other page is indicated by the user
642 **home.classlist**
643   a special version of the default page that lists the classes in the tracker
644 **classname.item**
645   displays an item of the *classname* class
646 **classname.index**
647   displays a list of *classname* items
648 **classname.search**
649   displays a search page for *classname* items
650 **_generic.index**
651   used to display a list of items where there is no *classname*.index available
652 **_generic.help**
653   used to display a "class help" page where there is no *classname*.help
654 **user.register**
655   a special page just for the user class that renders the registration page
656 **style.css**
657   a static file that is served up as-is
659 Note: Remember that you can create any template extension you want to, so 
660 if you just want to play around with the templating for new issues, you can
661 copy the current "issue.item" template to "issue.test", and then access the
662 test template using the ":template" URL argument::
664    http://your.tracker.example/tracker/issue?:template=test
666 and it won't affect your users using the "issue.item" template.
669 How the templates work
670 ----------------------
672 Basic Templating Actions
673 ~~~~~~~~~~~~~~~~~~~~~~~~
675 Roundup's templates consist of special attributes on your template tags.
676 These attributes form the Template Attribute Language, or TAL. The basic tag
677 commands are:
679 **tal:define="variable expression; variable expression; ..."**
680    Define a new variable that is local to this tag and its contents. For
681    example::
683       <html tal:define="title request/description">
684        <head><title tal:content="title"></title></head>
685       </html>
687    In the example, the variable "title" is defined as being the result of the
688    expression "request/description". The tal:content command inside the <html>
689    tag may then use the "title" variable.
691 **tal:condition="expression"**
692    Only keep this tag and its contents if the expression is true. For example::
694      <p tal:condition="python:request.user.hasPermission('View', 'issue')">
695       Display some issue information.
696      </p>
698    In the example, the <p> tag and its contents are only displayed if the
699    user has the View permission for issues. We consider the number zero, a
700    blank string, an empty list, and the built-in variable nothing to be false
701    values. Nearly every other value is true, including non-zero numbers, and
702    strings with anything in them (even spaces!).
704 **tal:repeat="variable expression"**
705    Repeat this tag and its contents for each element of the sequence that the
706    expression returns, defining a new local variable and a special "repeat"
707    variable for each element. For example::
709      <tr tal:repeat="u user/list">
710       <td tal:content="u/id"></td>
711       <td tal:content="u/username"></td>
712       <td tal:content="u/realname"></td>
713      </tr>
715    The example would iterate over the sequence of users returned by
716    "user/list" and define the local variable "u" for each entry.
718 **tal:replace="expression"**
719    Replace this tag with the result of the expression. For example::
721     <span tal:replace="request/user/realname"></span>
723    The example would replace the <span> tag and its contents with the user's
724    realname. If the user's realname was "Bruce" then the resultant output
725    would be "Bruce".
727 **tal:content="expression"**
728    Replace the contents of this tag with the result of the expression. For
729    example::
731     <span tal:content="request/user/realname">user's name appears here</span>
733    The example would replace the contents of the <span> tag with the user's
734    realname. If the user's realname was "Bruce" then the resultant output
735    would be "<span>Bruce</span>".
737 **tal:attributes="attribute expression; attribute expression; ..."**
738    Set attributes on this tag to the results of expressions. For example::
740      <a tal:attributes="href string:user${request/user/id}">My Details</a>
742    In the example, the "href" attribute of the <a> tag is set to the value of
743    the "string:user${request/user/id}" expression, which will be something
744    like "user123".
746 **tal:omit-tag="expression"**
747    Remove this tag (but not its contents) if the expression is true. For
748    example::
750       <span tal:omit-tag="python:1">Hello, world!</span>
752    would result in output of::
754       Hello, world!
756 Note that the commands on a given tag are evaulated in the order above, so
757 *define* comes before *condition*, and so on.
759 Additionally, a tag is defined, tal:block, which is removed from output. Its
760 content is not, but the tag itself is (so don't go using any tal:attributes
761 commands on it). This is useful for making arbitrary blocks of HTML
762 conditional or repeatable (very handy for repeating multiple table rows,
763 which would othewise require an illegal tag placement to effect the repeat).
766 Templating Expressions
767 ~~~~~~~~~~~~~~~~~~~~~~
769 The expressions you may use in the attibute values may be one of the following
770 forms:
772 **Path Expressions** - eg. ``item/status/checklist``
773    These are object attribute / item accesses. Roughly speaking, the path
774    ``item/status/checklist`` is broken into parts ``item``, ``status``
775    and ``checklist``. The ``item`` part is the root of the expression.
776    We then look for a ``status`` attribute on ``item``, or failing that, a
777    ``status`` item (as in ``item['status']``). If that
778    fails, the path expression fails. When we get to the end, the object we're
779    left with is evaluated to get a string - methods are called, objects are
780    stringified. Path expressions may have an optional ``path:`` prefix, though
781    they are the default expression type, so it's not necessary.
783    XXX | components of expressions
785    XXX "nothing" and "default"
787 **String Expressions** - eg. ``string:hello ${user/name}``
788    These expressions are simple string interpolations (though they can be just
789    plain strings with no interpolation if you want. The expression in the
790    ``${ ... }`` is just a path expression as above.
792 **Python Expressions** - eg. ``python: 1+1``
793    These expressions give the full power of Python. All the "root level"
794    variables are available, so ``python:item.status.checklist()`` would be
795    equivalent to ``item/status/checklist``, assuming that ``checklist`` is
796    a method.
798 Template Macros
799 ~~~~~~~~~~~~~~~
801 Macros are used in Roundup to save us from repeating the same common page
802 stuctures over and over. The most common (and probably only) macro you'll use
803 is the "icing" macro defined in the "page" template.
805 Macros are generated and used inside your templates using special attributes
806 similar to the `basic templating actions`_. In this case though, the
807 attributes belong to the Macro Expansion Template Attribute Language, or
808 METAL. The macro commands are:
810 **metal:define-macro="macro name"**
811   Define that the tag and its contents are now a macro that may be inserted
812   into other templates using the *use-macro* command. For example::
814     <html metal:define-macro="page">
815      ...
816     </html>
818   defines a macro called "page" using the ``<html>`` tag and its contents.
819   Once defined, macros are stored on the template they're defined on in the
820   ``macros`` attribute. You can access them later on through the ``templates``
821   variable, eg. the most common ``templates/page/macros/icing`` to access the
822   "page" macro of the "page" template.
824 **metal:use-macro="path expression"**
825   Use a macro, which is identified by the path expression (see above). This
826   will replace the current tag with the identified macro contents. For
827   example::
829    <tal:block metal:use-macro="templates/page/macros/icing">
830     ...
831    </tal:block>
833    will replace the tag and its contents with the "page" macro of the "page"
834    template.
836 **metal:define-slot="slot name"** and **metal:fill-slot="slot name"**
837   To define *dynamic* parts of the macro, you define "slots" which may be 
838   filled when the macro is used with a *use-macro* command. For example, the
839   ``templates/page/macros/icing`` macro defines a slot like so::
841     <title metal:define-slot="head_title">title goes here</title>
843   In your *use-macro* command, you may now use a *fill-slot* command like
844   this::
846     <title metal:fill-slot="head_title">My Title</title>
848   where the tag that fills the slot completely replaces the one defined as
849   the slot in the macro.
851 Note that you may not mix METAL and TAL commands on the same tag, but TAL
852 commands may be used freely inside METAL-using tags (so your *fill-slots*
853 tags may have all manner of TAL inside them).
856 Information available to templates
857 ----------------------------------
859 Note: this is implemented by roundup.cgi.templating.RoundupPageTemplate
861 The following variables are available to templates.
863 **context**
864   The current context. This is either None, a
865   `hyperdb class wrapper`_ or a `hyperdb item wrapper`_
866 **request**
867   Includes information about the current request, including:
868    - the url
869    - the current index information (``filterspec``, ``filter`` args,
870      ``properties``, etc) parsed out of the form. 
871    - methods for easy filterspec link generation
872    - *user*, the current user item as an HTMLItem instance
873    - *form*
874      The current CGI form information as a mapping of form argument
875      name to value
876 **tracker**
877   The current tracker
878 **db**
879   The current database, through which db.config may be reached.
880 **templates**
881   Access to all the tracker templates by name. Used mainly in *use-macro*
882   commands.
883 **utils**
884   This variable makes available some utility functions like batching.
885 **nothing**
886   This is a special variable - if an expression evaluates to this, then the
887   tag (in the case of a tal:replace), its contents (in the case of
888   tal:content) or some attributes (in the case of tal:attributes) will not
889   appear in the the output. So for example::
891     <span tal:attributes="class nothing">Hello, World!</span>
893   would result in::
895     <span>Hello, World!</span>
897 **default**
898   Also a special variable - if an expression evaluates to this, then the
899   existing HTML in the template will not be replaced or removed, it will
900   remain. So::
902     <span tal:replace="default">Hello, World!</span>
904   would result in::
906     <span>Hello, World!</span>
908 The context variable
909 ~~~~~~~~~~~~~~~~~~~~
911 The *context* variable is one of three things based on the current context
912 (see `determining web context`_ for how we figure this out):
914 1. if we're looking at a "home" page, then it's None
915 2. if we're looking at a specific hyperdb class, it's a
916    `hyperdb class wrapper`_.
917 3. if we're looking at a specific hyperdb item, it's a
918    `hyperdb item wrapper`_.
920 If the context is not None, we can access the properties of the class or item.
921 The only real difference between cases 2 and 3 above are:
923 1. the properties may have a real value behind them, and this will appear if
924    the property is displayed through ``context/property`` or
925    ``context/property/field``.
926 2. the context's "id" property will be a false value in the second case, but
927    a real, or true value in the third. Thus we can determine whether we're
928    looking at a real item from the hyperdb by testing "context/id".
930 Hyperdb class wrapper
931 :::::::::::::::::::::
933 Note: this is implemented by the roundup.cgi.templating.HTMLClass class.
935 This wrapper object provides access to a hyperb class. It is used primarily
936 in both index view and new item views, but it's also usable anywhere else that
937 you wish to access information about a class, or the items of a class, when
938 you don't have a specific item of that class in mind.
940 We allow access to properties. There will be no "id" property. The value
941 accessed through the property will be the current value of the same name from
942 the CGI form.
944 There are several methods available on these wrapper objects:
946 =========== =============================================================
947 Method      Description
948 =========== =============================================================
949 properties  return a `hyperdb property wrapper`_ for all of this class'
950             properties.
951 list        lists all of the active (not retired) items in the class.
952 csv         return the items of this class as a chunk of CSV text.
953 propnames   lists the names of the properties of this class.
954 filter      lists of items from this class, filtered and sorted
955             by the current *request* filterspec/filter/sort/group args
956 classhelp   display a link to a javascript popup containing this class'
957             "help" template.
958 submit      generate a submit button (and action hidden element)
959 renderWith  render this class with the given template.
960 history     returns 'New node - no history' :)
961 is_edit_ok  is the user allowed to Edit the current class?
962 is_view_ok  is the user allowed to View the current class?
963 =========== =============================================================
965 Note that if you have a property of the same name as one of the above methods,
966 you'll need to access it using a python "item access" expression. For example::
968    python:context['list']
970 will access the "list" property, rather than the list method.
973 Hyperdb item wrapper
974 ::::::::::::::::::::
976 Note: this is implemented by the roundup.cgi.templating.HTMLItem class.
978 This wrapper object provides access to a hyperb item.
980 We allow access to properties. There will be no "id" property. The value
981 accessed through the property will be the current value of the same name from
982 the CGI form.
984 There are several methods available on these wrapper objects:
986 =============== =============================================================
987 Method          Description
988 =============== =============================================================
989 submit          generate a submit button (and action hidden element)
990 journal         return the journal of the current item (**not implemented**)
991 history         render the journal of the current item as HTML
992 renderQueryForm specific to the "query" class - render the search form for
993                 the query
994 hasPermission   specific to the "user" class - determine whether the user
995                 has a Permission
996 is_edit_ok      is the user allowed to Edit the current item?
997 is_view_ok      is the user allowed to View the current item?
998 =============== =============================================================
1001 Note that if you have a property of the same name as one of the above methods,
1002 you'll need to access it using a python "item access" expression. For example::
1004    python:context['journal']
1006 will access the "journal" property, rather than the journal method.
1009 Hyperdb property wrapper
1010 ::::::::::::::::::::::::
1012 Note: this is implemented by subclasses roundup.cgi.templating.HTMLProperty
1013 class (HTMLStringProperty, HTMLNumberProperty, and so on).
1015 This wrapper object provides access to a single property of a class. Its
1016 value may be either:
1018 1. if accessed through a `hyperdb item wrapper`_, then it's a value from the
1019    hyperdb
1020 2. if access through a `hyperdb class wrapper`_, then it's a value from the
1021    CGI form
1024 The property wrapper has some useful attributes:
1026 =============== =============================================================
1027 Attribute       Description
1028 =============== =============================================================
1029 _name           the name of the property
1030 _value          the value of the property if any
1031 =============== =============================================================
1033 There are several methods available on these wrapper objects:
1035 =========== =================================================================
1036 Method      Description
1037 =========== =================================================================
1038 plain       render a "plain" representation of the property
1039 field       render a form edit field for the property
1040 stext       only on String properties - render the value of the
1041             property as StructuredText (requires the StructureText module
1042             to be installed separately)
1043 multiline   only on String properties - render a multiline form edit
1044             field for the property
1045 email       only on String properties - render the value of the 
1046             property as an obscured email address
1047 confirm     only on Password properties - render a second form edit field for
1048             the property, used for confirmation that the user typed the
1049             password correctly. Generates a field with name "name:confirm".
1050 reldate     only on Date properties - render the interval between the
1051             date and now
1052 pretty      only on Interval properties - render the interval in a
1053             pretty format (eg. "yesterday")
1054 menu        only on Link and Multilink properties - render a form select
1055             list for this property
1056 reverse     only on Multilink properties - produce a list of the linked
1057             items in reverse order
1058 =========== =================================================================
1060 The request variable
1061 ~~~~~~~~~~~~~~~~~~~~
1063 Note: this is implemented by the roundup.cgi.templating.HTMLRequest class.
1065 The request variable is packed with information about the current request.
1067 .. taken from roundup.cgi.templating.HTMLRequest docstring
1069 =========== =================================================================
1070 Variable    Holds
1071 =========== =================================================================
1072 form        the CGI form as a cgi.FieldStorage
1073 env         the CGI environment variables
1074 url         the current URL path for this request
1075 base        the base URL for this tracker
1076 user        a HTMLUser instance for this user
1077 classname   the current classname (possibly None)
1078 template    the current template (suffix, also possibly None)
1079 form        the current CGI form variables in a FieldStorage
1080 =========== =================================================================
1082 **Index page specific variables (indexing arguments)**
1084 =========== =================================================================
1085 Variable    Holds
1086 =========== =================================================================
1087 columns     dictionary of the columns to display in an index page
1088 show        a convenience access to columns - request/show/colname will
1089             be true if the columns should be displayed, false otherwise
1090 sort        index sort column (direction, column name)
1091 group       index grouping property (direction, column name)
1092 filter      properties to filter the index on
1093 filterspec  values to filter the index on
1094 search_text text to perform a full-text search on for an index
1095 =========== =================================================================
1097 There are several methods available on the request variable:
1099 =============== =============================================================
1100 Method          Description
1101 =============== =============================================================
1102 description     render a description of the request - handle for the page
1103                 title
1104 indexargs_form  render the current index args as form elements
1105 indexargs_url   render the current index args as a URL
1106 base_javascript render some javascript that is used by other components of
1107                 the templating
1108 batch           run the current index args through a filter and return a
1109                 list of items (see `hyperdb item wrapper`_, and
1110                 `batching`_)
1111 =============== =============================================================
1113 The form variable
1114 :::::::::::::::::
1116 The form variable is a little special because it's actually a python
1117 FieldStorage object. That means that you have two ways to access its
1118 contents. For example, to look up the CGI form value for the variable
1119 "name", use the path expression::
1121    request/form/name/value
1123 or the python expression::
1125    python:request.form['name'].value
1127 Note the "item" access used in the python case, and also note the explicit
1128 "value" attribute we have to access. That's because the form variables are
1129 stored as MiniFieldStorages. If there's more than one "name" value in
1130 the form, then the above will break since ``request/form/name`` is actually a
1131 *list* of MiniFieldStorages. So it's best to know beforehand what you're
1132 dealing with.
1135 The db variable
1136 ~~~~~~~~~~~~~~~
1138 Note: this is implemented by the roundup.cgi.templating.HTMLDatabase class.
1140 Allows access to all hyperdb classes as attributes of this variable. If you
1141 want access to the "user" class, for example, you would use::
1143   db/user
1144   python:db.user
1146 The access results in a `hyperdb class wrapper`_.
1148 The templates variable
1149 ~~~~~~~~~~~~~~~~~~~~~~
1151 Note: this is implemented by the roundup.cgi.templating.Templates class.
1153 This variable doesn't have any useful methods defined. It supports being
1154 used in expressions to access the templates, and subsequently the template
1155 macros. You may access the templates using the following path expression::
1157    templates/name
1159 or the python expression::
1161    templates[name]
1163 where "name" is the name of the template you wish to access. The template you
1164 get access to has one useful attribute, "macros". To access a specific macro
1165 (called "macro_name"), use the path expression::
1167    templates/name/macros/macro_name
1169 or the python expression::
1171    templates[name].macros[macro_name]
1174 The utils variable
1175 ~~~~~~~~~~~~~~~~~~
1177 Note: this is implemented by the roundup.cgi.templating.TemplatingUtils class.
1179 =============== =============================================================
1180 Method          Description
1181 =============== =============================================================
1182 Batch           return a batch object using the supplied list
1183 =============== =============================================================
1185 Batching
1186 ::::::::
1188 Use Batch to turn a list of items, or item ids of a given class, into a series
1189 of batches. Its usage is::
1191     python:util.Batch(sequence, size, start, end=0, orphan=0, overlap=0)
1193 or, to get the current index batch::
1195     request/batch
1197 The parameters are:
1199 ========= ==================================================================
1200 Parameter  Usage
1201 ========= ==================================================================
1202 sequence  a list of HTMLItems
1203 size      how big to make the sequence.
1204 start     where to start (0-indexed) in the sequence.
1205 end       where to end (0-indexed) in the sequence.
1206 orphan    if the next batch would contain less items than this
1207           value, then it is combined with this batch
1208 overlap   the number of items shared between adjacent batches
1209 ========= ==================================================================
1211 All of the parameters are assigned as attributes on the batch object. In
1212 addition, it has several more attributes:
1214 =============== ============================================================
1215 Attribute       Description
1216 =============== ============================================================
1217 start           indicates the start index of the batch. *Note: unlike the
1218                 argument, is a 1-based index (I know, lame)*
1219 first           indicates the start index of the batch *as a 0-based
1220                 index*
1221 length          the actual number of elements in the batch
1222 sequence_length the length of the original, unbatched, sequence.
1223 =============== ============================================================
1225 And several methods:
1227 =============== ============================================================
1228 Method          Description
1229 =============== ============================================================
1230 previous        returns a new Batch with the previous batch settings
1231 next            returns a new Batch with the next batch settings
1232 propchanged     detect if the named property changed on the current item
1233                 when compared to the last item
1234 =============== ============================================================
1236 An example of batching::
1238  <table class="otherinfo">
1239   <tr><th colspan="4" class="header">Existing Keywords</th></tr>
1240   <tr tal:define="keywords db/keyword/list"
1241       tal:repeat="start python:range(0, len(keywords), 4)">
1242    <td tal:define="batch python:utils.Batch(keywords, 4, start)"
1243        tal:repeat="keyword batch" tal:content="keyword/name">keyword here</td>
1244   </tr>
1245  </table>
1247 ... which will produce a table with four columns containing the items of the
1248 "keyword" class (well, their "name" anyway).
1250 Displaying Properties
1251 ---------------------
1253 Properties appear in the user interface in three contexts: in indices, in
1254 editors, and as search arguments.
1255 For each type of property, there are several display possibilities.
1256 For example, in an index view, a string property may just be
1257 printed as a plain string, but in an editor view, that property may be
1258 displayed in an editable field.
1261 Index Views
1262 -----------
1264 This is one of the class context views. It is also the default view for
1265 classes. The template used is "*classname*.index".
1267 Index View Specifiers
1268 ~~~~~~~~~~~~~~~~~~~~~
1270 An index view specifier (URL fragment) looks like this (whitespace has been
1271 added for clarity)::
1273      /issue?status=unread,in-progress,resolved&
1274             topic=security,ui&
1275             :group=+priority&
1276             :sort==activity&
1277             :filters=status,topic&
1278             :columns=title,status,fixer
1280 The index view is determined by two parts of the specifier: the layout part and
1281 the filter part. The layout part consists of the query parameters that begin
1282 with colons, and it determines the way that the properties of selected items
1283 are displayed. The filter part consists of all the other query parameters, and
1284 it determines the criteria by which items are selected for display.
1285 The filter part is interactively manipulated with the form widgets displayed in
1286 the filter section. The layout part is interactively manipulated by clicking on
1287 the column headings in the table.
1289 The filter part selects the union of the sets of items with values matching any
1290 specified Link properties and the intersection of the sets of items with values
1291 matching any specified Multilink properties.
1293 The example specifies an index of "issue" items. Only items with a "status" of
1294 either "unread" or "in-progres" or "resolved" are displayed, and only items
1295 with "topic" values including both "security" and "ui" are displayed. The items
1296 are grouped by priority, arranged in ascending order; and within groups, sorted
1297 by activity, arranged in descending order. The filter section shows filters for
1298 the "status" and "topic" properties, and the table includes columns for the
1299 "title", "status", and "fixer" properties.
1301 Filtering of indexes
1302 ~~~~~~~~~~~~~~~~~~~~
1304 TODO
1306 Searching Views
1307 ---------------
1309 This is one of the class context views. The template used is typically
1310 "*classname*.search".
1312 TODO
1314 Item Views
1315 ----------
1317 The basic view of a hyperdb item is provided by the "*classname*.item"
1318 template. It generally has three sections; an "editor", a "spool" and a
1319 "history" section.
1323 Editor Section
1324 ~~~~~~~~~~~~~~
1326 The editor section is used to manipulate the item - it may be a
1327 static display if the user doesn't have permission to edit the item.
1329 Here's an example of a basic editor template (this is the default "classic"
1330 template issue item edit form - from the "issue.item" template)::
1332  <table class="form">
1333  <tr>
1334   <th nowrap>Title</th>
1335   <td colspan=3 tal:content="structure python:context.title.field(size=60)">title</td>
1336  </tr>
1337  
1338  <tr>
1339   <th nowrap>Priority</th>
1340   <td tal:content="structure context/priority/menu">priority</td>
1341   <th nowrap>Status</th>
1342   <td tal:content="structure context/status/menu">status</td>
1343  </tr>
1344  
1345  <tr>
1346   <th nowrap>Superseder</th>
1347   <td>
1348    <span tal:replace="structure python:context.superseder.field(showid=1, size=20)" />
1349    <span tal:replace="structure python:db.issue.classhelp('id,title')" />
1350    <span tal:condition="context/superseder">
1351     <br>View: <span tal:replace="structure python:context.superseder.link(showid=1)" />
1352    </span>
1353   </td>
1354   <th nowrap>Nosy List</th>
1355   <td>
1356    <span tal:replace="structure context/nosy/field" />
1357    <span tal:replace="structure python:db.user.classhelp('username,realname,address,phone')" />
1358   </td>
1359  </tr>
1360  
1361  <tr>
1362   <th nowrap>Assigned To</th>
1363   <td tal:content="structure context/assignedto/menu">
1364    assignedto menu
1365   </td>
1366   <td>&nbsp;</td>
1367   <td>&nbsp;</td>
1368  </tr>
1369  
1370  <tr>
1371   <th nowrap>Change Note</th>
1372   <td colspan=3>
1373    <textarea name=":note" wrap="hard" rows="5" cols="60"></textarea>
1374   </td>
1375  </tr>
1376  
1377  <tr>
1378   <th nowrap>File</th>
1379   <td colspan=3><input type="file" name=":file" size="40"></td>
1380  </tr>
1381  
1382  <tr>
1383   <td>&nbsp;</td>
1384   <td colspan=3 tal:content="structure context/submit">
1385    submit button will go here
1386   </td>
1387  </tr>
1388  </table>
1391 When a change is submitted, the system automatically generates a message
1392 describing the changed properties. As shown in the example, the editor
1393 template can use the ":note" and ":file" fields, which are added to the
1394 standard change note message generated by Roundup.
1396 Spool Section
1397 ~~~~~~~~~~~~~
1399 The spool section lists related information like the messages and files of
1400 an issue.
1402 TODO
1405 History Section
1406 ~~~~~~~~~~~~~~~
1408 The final section displayed is the history of the item - its database journal.
1409 This is generally generated with the template::
1411  <tal:block tal:replace="structure context/history" />
1413 *To be done:*
1415 *The actual history entries of the item may be accessed for manual templating
1416 through the "journal" method of the item*::
1418  <tal:block tal:repeat="entry context/journal">
1419   a journal entry
1420  </tal:block>
1422 *where each journal entry is an HTMLJournalEntry.*
1424 Defining new web actions
1425 ------------------------
1427 XXX
1430 Access Controls
1431 ===============
1433 A set of Permissions are built in to the security module by default:
1435 - Edit (everything)
1436 - View (everything)
1438 The default interfaces define:
1440 - Web Registration
1441 - Web Access
1442 - Web Roles
1443 - Email Registration
1444 - Email Access
1446 These are hooked into the default Roles:
1448 - Admin (Edit everything, View everything, Web Roles)
1449 - User (Web Access, Email Access)
1450 - Anonymous (Web Registration, Email Registration)
1452 And finally, the "admin" user gets the "Admin" Role, and the "anonymous" user
1453 gets the "Anonymous" assigned when the database is initialised on installation.
1454 The two default schemas then define:
1456 - Edit issue, View issue (both)
1457 - Edit file, View file (both)
1458 - Edit msg, View msg (both)
1459 - Edit support, View support (extended only)
1461 and assign those Permissions to the "User" Role. New users are assigned the
1462 Roles defined in the config file as:
1464 - NEW_WEB_USER_ROLES
1465 - NEW_EMAIL_USER_ROLES
1467 You may alter the configuration variables to change the Role that new web or
1468 email users get, for example to not give them access to the web interface if
1469 they register through email.
1471 You may use the ``roundup-admin`` "``security``" command to display the
1472 current Role and Permission configuration in your tracker.
1474 Adding a new Permission
1475 -----------------------
1477 When adding a new Permission, you will need to:
1479 1. add it to your tracker's dbinit so it is created
1480 2. enable it for the Roles that should have it (verify with
1481    "``roundup-admin security``")
1482 3. add it to the relevant HTML interface templates
1483 4. add it to the appropriate xxxPermission methods on in your tracker
1484    interfaces module
1486 Example Scenarios
1487 -----------------
1489 **automatic registration of users in the e-mail gateway**
1490  By giving the "anonymous" user the "Email Registration" Role, any
1491  unidentified user will automatically be registered with the tracker (with
1492  no password, so they won't be able to log in through the web until an admin
1493  sets them a password). Note: this is the default behaviour in the tracker
1494  templates that ship with Roundup.
1496 **anonymous access through the e-mail gateway**
1497  Give the "anonymous" user the "Email Access" and ("Edit", "issue") Roles
1498  but not giving them the "Email Registration" Role. This means that when an
1499  unknown user sends email into the tracker, they're automatically logged in
1500  as "anonymous". Since they don't have the "Email Registration" Role, they
1501  won't be automatically registered, but since "anonymous" has permission
1502  to use the gateway, they'll still be able to submit issues. Note that the
1503  Sender information - their email address - will not be available - they're
1504  *anonymous*.
1506 XXX more examples needed
1509 Examples
1510 ========
1512 Adding a new field to the classic schema
1513 ----------------------------------------
1515 This example shows how to add a new constrained property (ie. a selection of
1516 distinct values) to your tracker.
1518 Introduction
1519 ~~~~~~~~~~~~
1521 To make the classic schema of roundup useful as a todo tracking system
1522 for a group of systems administrators, it needed an extra data field
1523 per issue: a category.
1525 This would let sysads quickly list all todos in their particular
1526 area of interest without having to do complex queries, and without
1527 relying on the spelling capabilities of other sysads (a losing
1528 proposition at best).
1530 Adding a field to the database
1531 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1533 This is the easiest part of the change. The category would just be a plain
1534 string, nothing fancy. To change what is in the database you need to add
1535 some lines to the ``open()`` function in ``dbinit.py``::
1537     category = Class(db, "category", name=String())
1538     category.setkey("name")
1540 Here we are setting up a chunk of the database which we are calling
1541 "category". It contains a string, which we are refering to as "name" for
1542 lack of a more imaginative title. Then we are setting the key of this chunk
1543 of the database to be that "name". This is equivalent to an index for
1544 database types. This also means that there can only be one category with a
1545 given name.
1547 Adding the above lines allows us to create categories, but they're not tied
1548 to the issues that we are going to be creating. It's just a list of categories
1549 off on its own, which isn't much use. We need to link it in with the issues.
1550 To do that, find the lines in the ``open()`` function in ``dbinit.py`` which
1551 set up the "issue" class, and then add a link to the category::
1553     issue = IssueClass(db, "issue", ... , category=Multilink("category"), ... )
1555 The Multilink() means that each issue can have many categories. If you were
1556 adding something with a more one to one relationship use Link() instead.
1558 That is all you need to do to change the schema. The rest of the effort is
1559 fiddling around so you can actually use the new category.
1561 Setting up security on the new objects
1562 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1564 By default only the admin user can look at and change objects. This doesn't
1565 suit us, as we want any user to be able to create new categories as
1566 required, and obviously everyone needs to be able to view the categories of
1567 issues for it to be useful.
1569 We therefore need to change the security of the category objects. This is
1570 also done in the ``open()`` function of ``dbinit.py``.
1572 There are currently two loops which set up permissions and then assign them
1573 to various roles. Simply add the new "category" to both lists::
1575     # new permissions for this schema
1576     for cl in 'issue', 'file', 'msg', 'user', 'category':
1577         db.security.addPermission(name="Edit", klass=cl,
1578             description="User is allowed to edit "+cl)
1579         db.security.addPermission(name="View", klass=cl,
1580             description="User is allowed to access "+cl)
1582     # Assign the access and edit permissions for issue, file and message
1583     # to regular users now
1584     for cl in 'issue', 'file', 'msg', 'category':
1585         p = db.security.getPermission('View', cl)
1586         db.security.addPermissionToRole('User', p)
1587         p = db.security.getPermission('Edit', cl)
1588         db.security.addPermissionToRole('User', p)
1590 So you are in effect doing the following::
1592     db.security.addPermission(name="Edit", klass='category',
1593         description="User is allowed to edit "+'category')
1594     db.security.addPermission(name="View", klass='category',
1595         description="User is allowed to access "+'category')
1597 which is creating two permission types; that of editing and viewing
1598 "category" objects respectively. Then the following lines assign those new
1599 permissions to the "User" role, so that normal users can view and edit
1600 "category" objects::
1602     p = db.security.getPermission('View', 'category')
1603     db.security.addPermissionToRole('User', p)
1605     p = db.security.getPermission('Edit', 'category')
1606     db.security.addPermissionToRole('User', p)
1608 This is all the work that needs to be done for the database. It will store
1609 categories, and let users view and edit them. Now on to the interface
1610 stuff.
1612 Changing the web left hand frame
1613 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1615 We need to give the users the ability to create new categories, and the
1616 place to put the link to this functionality is in the left hand function
1617 bar, under the "Issues" area. The file that defines how this area looks is
1618 ``html/page``, which is what we are going to be editing next.
1620 If you look at this file you can see that it contains a lot of "classblock"
1621 sections which are chunks of HTML that will be included or excluded in the
1622 output depending on whether the condition in the classblock is met. Under
1623 the end of the classblock for issue is where we are going to add the
1624 category code::
1626   <p class="classblock"
1627      tal:condition="python:request.user.hasPermission('View', 'category')">
1628    <b>Categories</b><br>
1629    <a tal:condition="python:request.user.hasPermission('Edit', 'category')"
1630       href="category?:template=item">New Category<br></a>
1631   </p>
1633 The first two lines is the classblock definition, which sets up a condition
1634 that only users who have "View" permission to the "category" object will
1635 have this section included in their output. Next comes a plain "Categories"
1636 header in bold. Everyone who can view categories will get that.
1638 Next comes the link to the editing area of categories. This link will only
1639 appear if the condition is matched: that condition being that the user has
1640 "Edit" permissions for the "category" objects. If they do have permission
1641 then they will get a link to another page which will let the user add new
1642 categories.
1644 Note that if you have permission to view but not edit categories then all
1645 you will see is a "Categories" header with nothing underneath it. This is
1646 obviously not very good interface design, but will do for now. I just claim
1647 that it is so I can add more links in this section later on. However to fix
1648 the problem you could change the condition in the classblock statement, so
1649 that only users with "Edit" permission would see the "Categories" stuff.
1651 Setting up a page to edit categories
1652 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1654 We defined code in the previous section which let users with the
1655 appropriate permissions see a link to a page which would let them edit
1656 conditions. Now we have to write that page.
1658 The link was for the item template for the category object. This translates
1659 into the system looking for a file called ``category.item`` in the ``html``
1660 tracker directory. This is the file that we are going to write now.
1662 First we add an info tag in a comment which doesn't affect the outcome
1663 of the code at all but is useful for debugging. If you load a page in a
1664 browser and look at the page source, you can see which sections come
1665 from which files by looking for these comments::
1667     <!-- category.item -->
1669 Next we need to add in the METAL macro stuff so we get the normal page
1670 trappings::
1672  <tal:block metal:use-macro="templates/page/macros/icing">
1673   <title metal:fill-slot="head_title">Category editing</title>
1674   <td class="page-header-top" metal:fill-slot="body_title">
1675    <h2>Category editing</h2>
1676   </td>
1677   <td class="content" metal:fill-slot="content">
1679 Next we need to setup up a standard HTML form, which is the whole
1680 purpose of this file. We link to some handy javascript which sends the form
1681 through only once. This is to stop users hitting the send button
1682 multiple times when they are impatient and thus having the form sent
1683 multiple times::
1685     <form method="POST" onSubmit="return submit_once()"
1686           enctype="multipart/form-data">
1688 Next we define some code which sets up the minimum list of fields that we
1689 require the user to enter. There will be only one field, that of "name", so
1690 they user better put something in it otherwise the whole form is pointless::
1692     <input type="hidden" name=":required" value="name">
1694 To get everything to line up properly we will put everything in a table,
1695 and put a nice big header on it so the user has an idea what is happening::
1697     <table class="form">
1698      <tr><th class="header" colspan=2>Category</th></tr>
1700 Next we need the actual field that the user is going to enter the new
1701 category. The "context.name.field(size=60)" bit tells roundup to generate a
1702 normal HTML field of size 60, and the contents of that field will be the
1703 "name" variable of the current context (which is "category"). The upshot of
1704 this is that when the user types something in to the form, a new category
1705 will be created with that name::
1707     <tr>
1708      <th nowrap>Name</th>
1709      <td tal:content="structure python:context.name.field(size=60)">name</td>
1710     </tr>
1712 Then a submit button so that the user can submit the new category::
1714     <tr>
1715      <td>&nbsp;</td>
1716      <td colspan=3 tal:content="structure context/submit">
1717       submit button will go here
1718      </td>
1719     </tr>
1721 Finally we finish off the tags we used at the start to do the METAL stuff::
1723   </td>
1724  </tal:block>
1726 So putting it all together, and closing the table and form we get::
1728  <!-- category.item -->
1729  <tal:block metal:use-macro="templates/page/macros/icing">
1730   <title metal:fill-slot="head_title">Category editing</title>
1731   <td class="page-header-top" metal:fill-slot="body_title">
1732    <h2>Category editing</h2>
1733   </td>
1734   <td class="content" metal:fill-slot="content">
1735    <form method="POST" onSubmit="return submit_once()"
1736          enctype="multipart/form-data">
1738     <input type="hidden" name=":required" value="name">
1740     <table class="form">
1741      <tr><th class="header" colspan=2>Category</th></tr>
1743      <tr>
1744       <th nowrap>Name</th>
1745       <td tal:content="structure python:context.name.field(size=60)">name</td>
1746      </tr>
1748      <tr>
1749       <td>&nbsp;</td>
1750       <td colspan=3 tal:content="structure context/submit">
1751        submit button will go here
1752       </td>
1753      </tr>
1754     </table>
1755    </form>
1756   </td>
1757  </tal:block>
1759 This is quite a lot to just ask the user one simple question, but
1760 there is a lot of setup for basically one line (the form line) to do
1761 its work. To add another field to "category" would involve one more line
1762 (well maybe a few extra to get the formatting correct).
1764 Adding the category to the issue
1765 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1767 We now have the ability to create issues to our hearts content, but
1768 that is pointless unless we can assign categories to issues.  Just like
1769 the ``html/category.item`` file was used to define how to add a new
1770 category, the ``html/issue.item`` is used to define how a new issue is
1771 created.
1773 Just like ``category.issue`` this file defines a form which has a table to lay
1774 things out. It doesn't matter where in the table we add new stuff,
1775 it is entirely up to your sense of aesthetics::
1777    <th nowrap>Category</th>
1778    <td><span tal:replace="structure context/category/field" />
1779        <span tal:replace="structure db/category/classhelp" />
1780    </td>
1782 First we define a nice header so that the user knows what the next section
1783 is, then the middle line does what we are most interested in. This
1784 ``context/category/field`` gets replaced with a field which contains the
1785 category in the current context (the current context being the new issue).
1787 The classhelp lines generate a link (labelled "list") to a popup window
1788 which contains the list of currently known categories.
1790 Searching on categories
1791 ~~~~~~~~~~~~~~~~~~~~~~~
1793 We can add categories, and create issues with categories. The next obvious
1794 thing that we would like to be would be to search issues based on their
1795 category, so that any one working on the web server could look at all
1796 issues in the category "Web" for example.
1798 If you look in the html/page file and look for the "Search Issues" you will
1799 see that it looks something like ``<a href="issue?:template=search">Search
1800 Issues</a>`` which shows us that when you click on "Search Issues" it will
1801 be looking for a ``issue.search`` file to display. So that is indeed the file
1802 that we are going to change.
1804 If you look at this file it should be starting to seem familiar. It is a
1805 simple HTML form using a table to define structure. You can add the new
1806 category search code anywhere you like within that form::
1808     <tr>
1809      <th>Category:</th>
1810      <td>
1811       <select name="category">
1812        <option value="">don't care</option>
1813        <option value="">------------</option>
1814        <option tal:repeat="s db/category/list" tal:attributes="value s/name"
1815                tal:content="s/name">category to filter on</option>
1816       </select>
1817      </td>
1818      <td><input type="checkbox" name=":columns" value="category" checked></td>
1819      <td><input type="radio" name=":sort" value="category"></td>
1820      <td><input type="radio" name=":group" value="category"></td>
1821     </tr>
1823 Most of this is straightforward to anyone who knows HTML. It is just
1824 setting up a select list followed by a checkbox and a couple of radio
1825 buttons. 
1827 The ``tal:repeat`` part repeats the tag for every item in the "category"
1828 table and setting "s" to be each category in turn.
1830 The ``tal:attributes`` part is setting up the ``value=`` part of the option tag
1831 to be the name part of "s" which is the current category in the loop.
1833 The ``tal:content`` part is setting the contents of the option tag to be the
1834 name part of "s" again. For objects more complex than category, obviously
1835 you would put an id in the value, and the descriptive part in the content;
1836 but for category they are the same.
1838 Adding category to the default view
1839 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1841 We can now add categories, add issues with categories, and search issues
1842 based on categories. This is everything that we need to do, however there
1843 is some more icing that we would like. I think the category of an issue is
1844 important enough that it should be displayed by default when listing all
1845 the issues.
1847 Unfortunately, this is a bit less obvious than the previous steps. The code
1848 defining how the issues look is in ``html/issue.index``. This is a large table
1849 with a form down the bottom for redisplaying and so forth. 
1851 Firstly we need to add an appropriate header to the start of the table::
1853     <th tal:condition="request/show/category">Category</th>
1855 The condition part of this statement is so that if the user has selected
1856 not to see the Category column then they won't.
1858 The rest of the table is a loop which will go through every issue that
1859 matches the display criteria. The loop variable is "i" - which means that
1860 every issue gets assigned to "i" in turn.
1862 The new part of code to display the category will look like this::
1864     <td tal:condition="request/show/category" tal:content="i/category"></td>
1866 The condition is the same as above: only display the condition when the
1867 user hasn't asked for it to be hidden. The next part is to set the content
1868 of the cell to be the category part of "i" - the current issue.
1870 Finally we have to edit ``html/page`` again. This time to tell it that when the
1871 user clicks on "Unnasigned Issues" or "All Issues" that the category should
1872 be displayed. If you scroll down the page file, you can see the links with
1873 lots of options. The option that we are interested in is the ``:columns=`` one
1874 which tells roundup which fields of the issue to display. Simply add
1875 "category" to that list and it all should work.
1878 Adding in state transition control
1879 ----------------------------------
1881 Sometimes tracker admins want to control the states that users may move issues
1882 to.
1884 1. add a Multilink property to the status class::
1886      stat = Class(db, "status", ... , transitions=Multilink('status'), ...)
1888    and then edit the statuses already created through the web using the
1889    generic class list / CSV editor.
1891 2. add an auditor module ``checktransition.py`` in your tracker's
1892    ``detectors`` directory::
1894      def checktransition(db, cl, nodeid, newvalues):
1895          ''' Check that the desired transition is valid for the "status"
1896              property.
1897          '''
1898          if not newvalues.has_key('status'):
1899              return
1900          current = cl.get(nodeid, 'status')
1901          new = newvalues['status']
1902          if new == current:
1903              return
1904          ok = db.status.get(current, 'transitions')
1905          if new not in ok:
1906              raise ValueError, 'Status not allowed to move from "%s" to "%s"'%(
1907                  db.status.get(current, 'name'), db.status.get(new, 'name'))
1909      def init(db):
1910          db.issue.audit('set', checktransition)
1912 3. in the ``issue.item`` template, change the status editing bit from::
1914     <th nowrap>Status</th>
1915     <td tal:content="structure context/status/menu">status</td>
1917    to::
1919     <th nowrap>Status</th>
1920     <td>
1921      <select tal:condition="context/id" name="status">
1922       <tal:block tal:define="ok context/status/transitions"
1923                  tal:repeat="state db/status/list">
1924        <option tal:condition="python:state.id in ok"
1925                tal:attributes="value state/id;
1926                                selected python:state.id == context.status.id"
1927                tal:content="state/name"></option>
1928       </tal:block>
1929      </select>
1930      <tal:block tal:condition="not:context/id"
1931                 tal:replace="structure context/status/menu" />
1932     </td>
1934    which displays only the allowed status to transition to.
1937 Displaying entire message contents in the issue display
1938 -------------------------------------------------------
1940 Alter the issue.item template section for messages to::
1942  <table class="messages" tal:condition="context/messages">
1943   <tr><th colspan=3 class="header">Messages</th></tr>
1944   <tal:block tal:repeat="msg context/messages/reverse">
1945    <tr>
1946     <th><a tal:attributes="href string:msg${msg/id}"
1947            tal:content="string:msg${msg/id}"></a></th>
1948     <th tal:content="string:Author: ${msg/author}">author</th>
1949     <th tal:content="string:Date: ${msg/date}">date</th>
1950    </tr>
1951    <tr>
1952     <td colspan="3" class="content">
1953      <pre tal:content="msg/content">content</pre>
1954     </td>
1955    </tr>
1956   </tal:block>
1957  </table>
1959 Restricting the list of users that are assignable to a task
1960 -----------------------------------------------------------
1962 1. In your tracker's "dbinit.py", create a new Role, say "Developer"::
1964      db.security.addRole(name='Developer', description='A developer')
1966 2. Just after that, create a new Permission, say "Fixer", specific to "issue"::
1968      p = db.security.addPermission(name='Fixer', klass='issue',
1969          description='User is allowed to be assigned to fix issues')
1971 3. Then assign the new Permission to your "Developer" Role::
1973      db.security.addPermissionToRole('Developer', p)
1975 4. In the issue item edit page ("html/issue.item" in your tracker dir), use
1976    the new Permission in restricting the "assignedto" list::
1978     <select name="assignedto">
1979      <option value="-1">- no selection -</option>
1980      <tal:block tal:repeat="user db/user/list">
1981      <option tal:condition="python:user.hasPermission('Fixer', context.classname)"
1982              tal:attributes="value user/id;
1983                              selected python:user.id == context.assignedto"
1984              tal:content="user/realname"></option>
1985      </tal:block>
1986     </select>
1988 For extra security, you may wish to set up an auditor to enforce the
1989 Permission requirement (install this as "assignedtoFixer.py" in your tracker
1990 "detectors" directory)::
1992   def assignedtoMustBeFixer(db, cl, nodeid, newvalues):
1993       ''' Ensure the assignedto value in newvalues is a used with the Fixer
1994           Permission
1995       '''
1996       if not newvalues.has_key('assignedto'):
1997           # don't care
1998           return
1999   
2000       # get the userid
2001       userid = newvalues['assignedto']
2002       if not db.security.hasPermission('Fixer', userid, cl.classname):
2003           raise ValueError, 'You do not have permission to edit %s'%cl.classname
2005   def init(db):
2006       db.issue.audit('set', assignedtoMustBeFixer)
2007       db.issue.audit('create', assignedtoMustBeFixer)
2009 So now, if the edit attempts to set the assignedto to a user that doesn't have
2010 the "Fixer" Permission, the error will be raised.
2013 Setting up a "wizard" (or "druid") for controlled adding of issues
2014 ------------------------------------------------------------------
2016 1. Set up the page templates you wish to use for data input. My wizard
2017    is going to be a two-step process, first figuring out what category of
2018    issue the user is submitting, and then getting details specific to that
2019    category. The first page includes a table of help, explaining what the
2020    category names mean, and then the core of the form::
2022     <form method="POST" onSubmit="return submit_once()"
2023           enctype="multipart/form-data">
2024       <input type="hidden" name=":template" value="add_page1">
2025       <input type="hidden" name=":action" value="page1submit">
2027       <strong>Category:</strong>
2028       <tal:block tal:replace="structure context/category/menu" />
2029       <input type="submit" value="Continue">
2030     </form>
2032    The next page has the usual issue entry information, with the addition of
2033    the following form fragments::
2035     <form method="POST" onSubmit="return submit_once()"
2036           enctype="multipart/form-data" tal:condition="context/is_edit_ok"
2037           tal:define="cat request/form/category/value">
2039       <input type="hidden" name=":template" value="add_page2">
2040       <input type="hidden" name=":required" value="title">
2041       <input type="hidden" name="category" tal:attributes="value cat">
2043        .
2044        .
2045        .
2046     </form>
2048    Note that later in the form, I test the value of "cat" include form
2049    elements that are appropriate. For example::
2051     <tal:block tal:condition="python:cat in '6 10 13 14 15 16 17'.split()">
2052      <tr>
2053       <th nowrap>Operating System</th>
2054       <td tal:content="structure context/os/field"></td>
2055      </tr>
2056      <tr>
2057       <th nowrap>Web Browser</th>
2058       <td tal:content="structure context/browser/field"></td>
2059      </tr>
2060     </tal:block>
2062    ... the above section will only be displayed if the category is one of 6,
2063    10, 13, 14, 15, 16 or 17.
2065 3. Determine what actions need to be taken between the pages - these are
2066    usually to validate user choices and determine what page is next. Now
2067    encode those actions in methods on the interfaces Client class and insert
2068    hooks to those actions in the "actions" attribute on that class, like so::
2070     actions = client.Class.actions + (
2071         ('page1_submit', page1SubmitAction),
2072     )
2074     def page1SubmitAction(self):
2075         ''' Verify that the user has selected a category, and then move on
2076             to page 2.
2077         '''
2078         category = self.form['category'].value
2079         if category == '-1':
2080             self.error_message.append('You must select a category of report')
2081             return
2082         # everything's ok, move on to the next page
2083         self.template = 'add_page2'
2085 4. Use the usual "new" action as the :action on the final page, and you're
2086    done (the standard context/submit method can do this for you).
2088 -------------------
2090 Back to `Table of Contents`_
2092 .. _`Table of Contents`: index.html