Code

- Extended getuid() to replace figure_curuserid().
[roundup.git] / doc / customizing.txt
1 ===================
2 Customising Roundup
3 ===================
5 :Version: $Revision: 1.97 $
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
56 configuration for the web and e-mail components of roundup's interfaces.
57 As the name suggests, this file is a Python module. This means that any
58 valid python expression may be used in the file. Mostly though, you'll
59 be setting the configuration variables to string values. Python string
60 values must be quoted with either single or double quotes::
62    'this is a string'
63    "this is also a string - use it when the value has 'single quotes'"
64    this is not a string - it's not quoted
66 Python strings may use formatting that's almost identical to C string
67 formatting. The ``%`` operator is used to perform the formatting, like
68 so::
70     'roundup-admin@%s'%MAIL_DOMAIN
72 this will create a string ``'roundup-admin@tracker.domain.example'`` if
73 MAIL_DOMAIN is set to ``'tracker.domain.example'``.
75 You'll also note some values are set to::
77    os.path.join(TRACKER_HOME, 'db')
79 or similar. This creates a new string which holds the path to the
80 ``'db'`` directory in the TRACKER_HOME directory. This is just a
81 convenience so if the TRACKER_HOME changes you don't have to edit
82 multiple valoues.
84 The configuration variables available are:
86 **TRACKER_HOME** - ``os.path.split(__file__)[0]``
87  The tracker home directory. The above default code will automatically
88  determine the tracker home for you, so you can just leave it alone.
90 **MAILHOST** - ``'localhost'``
91  The SMTP mail host that roundup will use to send e-mail.
93 **MAILUSER** - ``()``
94  If your SMTP mail host requires a username and password for access, then
95  specify them here. eg. ``MAILUSER = ('username', 'password')``
97 **MAILHOST_TLS** - ``'no'``
98  If your SMTP mail host provides or requires TLS (Transport Layer
99  Security) then set ``MAILHOST_TLS = 'yes'``
101 **MAILHOST_TLS_KEYFILE** - ``''``
102  If you're using TLS, you may also set MAILHOST_TLS_KEYFILE to the name of
103  a PEM formatted file that contains your private key.
105 **MAILHOST_TLS_CERTFILE** - ``''``
106  If you're using TLS and have specified a MAILHOST_TLS_KEYFILE, you may
107  also set MAILHOST_TLS_CERTFILE to the name of a PEM formatted certificate
108  chain file.
110 **MAIL_DOMAIN** - ``'tracker.domain.example'``
111  The domain name used for email addresses.
113 **DATABASE** - ``os.path.join(TRACKER_HOME, 'db')``
114  This is the directory that the database is going to be stored in. By default
115  it is in the tracker home.
117 **TEMPLATES** - ``os.path.join(TRACKER_HOME, 'html')``
118  This is the directory that the HTML templates reside in. By default they are
119  in the tracker home.
121 **TRACKER_NAME** - ``'Roundup issue tracker'``
122  A descriptive name for your roundup tracker. This is sent out in e-mails and
123  appears in the heading of CGI pages.
125 **TRACKER_EMAIL** - ``'issue_tracker@%s'%MAIL_DOMAIN``
126  The email address that e-mail sent to roundup should go to. Think of it as the
127  tracker's personal e-mail address.
129 **TRACKER_WEB** - ``'http://tracker.example/cgi-bin/roundup.cgi/bugs/'``
130  The web address that the tracker is viewable at. This will be included in
131  information sent to users of the tracker. The URL **must** include the
132  cgi-bin part or anything else that is required to get to the home page of
133  the tracker. You **must** include a trailing '/' in the URL.
135 **ADMIN_EMAIL** - ``'roundup-admin@%s'%MAIL_DOMAIN``
136  The email address that roundup will complain to if it runs into trouble.
138 **EMAIL_FROM_TAG** - ``''``
139  Additional text to include in the "name" part of the ``From:`` address used
140  in nosy messages. If the sending user is "Foo Bar", the ``From:`` line is
141  usually::
143     "Foo Bar" <issue_tracker@tracker.example>
145  The EMAIL_FROM_TAG goes inside the "Foo Bar" quotes like so::
147     "Foo Bar EMAIL_FROM_TAG" <issue_tracker@tracker.example>
149 **MESSAGES_TO_AUTHOR** - ``'new'``, ``'yes'`` or``'no'``
150  Send nosy messages to the author of the message?
151  If 'new' is used, then the author will only be sent the message when the
152  message creates a new issue. If 'yes' then the author will always be sent
153  a copy of the message they wrote.
155 **ADD_AUTHOR_TO_NOSY** - ``'new'``, ``'yes'`` or ``'no'``
156  Does the author of a message get placed on the nosy list automatically?
157  If ``'new'`` is used, then the author will only be added when a message
158  creates a new issue. If ``'yes'``, then the author will be added on followups
159  too. If ``'no'``, they're never added to the nosy.
161 **ADD_RECIPIENTS_TO_NOSY** - ``'new'``, ``'yes'`` or ``'no'``
162  Do the recipients (To:, Cc:) of a message get placed on the nosy list?
163  If ``'new'`` is used, then the recipients will only be added when a message
164  creates a new issue. If ``'yes'``, then the recipients will be added on
165  followups too. If ``'no'``, they're never added to the nosy.
167 **EMAIL_SIGNATURE_POSITION** - ``'top'``, ``'bottom'`` or ``'none'``
168  Where to place the email signature in messages that Roundup generates.
170 **EMAIL_KEEP_QUOTED_TEXT** - ``'yes'`` or ``'no'``
171  Keep email citations. Citations are the part of e-mail which the sender has
172  quoted in their reply to previous e-mail.
174 **EMAIL_LEAVE_BODY_UNCHANGED** - ``'no'``
175  Preserve the email body as is. Enabiling this will cause the entire message
176  body to be stored, including all citations and signatures. It should be
177  either ``'yes'`` or ``'no'``.
179 **MAIL_DEFAULT_CLASS** - ``'issue'`` or ``''``
180  Default class to use in the mailgw if one isn't supplied in email
181  subjects. To disable, comment out the variable below or leave it blank.
183 The default config.py is given below - as you
184 can see, the MAIL_DOMAIN must be edited before any interaction with the
185 tracker is attempted.::
187     # roundup home is this package's directory
188     TRACKER_HOME=os.path.split(__file__)[0]
190     # The SMTP mail host that roundup will use to send mail
191     MAILHOST = 'localhost'
193     # The domain name used for email addresses.
194     MAIL_DOMAIN = 'your.tracker.email.domain.example'
196     # This is the directory that the database is going to be stored in
197     DATABASE = os.path.join(TRACKER_HOME, 'db')
199     # This is the directory that the HTML templates reside in
200     TEMPLATES = os.path.join(TRACKER_HOME, 'html')
202     # A descriptive name for your roundup tracker
203     TRACKER_NAME = 'Roundup issue tracker'
205     # The email address that mail to roundup should go to
206     TRACKER_EMAIL = 'issue_tracker@%s'%MAIL_DOMAIN
208     # The web address that the tracker is viewable at. This will be
209     # included in information sent to users of the tracker. The URL MUST
210     # include the cgi-bin part or anything else that is required to get
211     # to the home page of the tracker. You MUST include a trailing '/'
212     # in the URL.
213     TRACKER_WEB = 'http://tracker.example/cgi-bin/roundup.cgi/bugs/'
215     # The email address that roundup will complain to if it runs into
216     # trouble
217     ADMIN_EMAIL = 'roundup-admin@%s'%MAIL_DOMAIN
219     # Additional text to include in the "name" part of the From: address
220     # used in nosy messages. If the sending user is "Foo Bar", the From:
221     # line is usually: "Foo Bar" <issue_tracker@tracker.example>
222     # the EMAIL_FROM_TAG goes inside the "Foo Bar" quotes like so:
223     #    "Foo Bar EMAIL_FROM_TAG" <issue_tracker@tracker.example>
224     EMAIL_FROM_TAG = ""
226     # Send nosy messages to the author of the message
227     MESSAGES_TO_AUTHOR = 'no'           # either 'yes' or 'no'
229     # Does the author of a message get placed on the nosy list
230     # automatically? If 'new' is used, then the author will only be
231     # added when a message creates a new issue. If 'yes', then the
232     # author will be added on followups too. If 'no', they're never
233     # added to the nosy.
234     ADD_AUTHOR_TO_NOSY = 'new'          # one of 'yes', 'no', 'new'
236     # Do the recipients (To:, Cc:) of a message get placed on the nosy
237     # list? If 'new' is used, then the recipients will only be added
238     # when a message creates a new issue. If 'yes', then the recipients
239     # will be added on followups too. If 'no', they're never added to
240     # the nosy.
241     ADD_RECIPIENTS_TO_NOSY = 'new'      # either 'yes', 'no', 'new'
243     # Where to place the email signature
244     EMAIL_SIGNATURE_POSITION = 'bottom' # one of 'top', 'bottom', 'none'
246     # Keep email citations
247     EMAIL_KEEP_QUOTED_TEXT = 'no'       # either 'yes' or 'no'
249     # Preserve the email body as is
250     EMAIL_LEAVE_BODY_UNCHANGED = 'no'   # either 'yes' or 'no'
252     # Default class to use in the mailgw if one isn't supplied in email
253     # subjects. To disable, comment out the variable below or leave it
254     # blank. Examples:
255     MAIL_DEFAULT_CLASS = 'issue'   # use "issue" class by default
256     #MAIL_DEFAULT_CLASS = ''        # disable (or just comment the var out)
258     # 
259     # SECURITY DEFINITIONS
260     #
261     # define the Roles that a user gets when they register with the
262     # tracker these are a comma-separated string of role names (e.g.
263     # 'Admin,User')
264     NEW_WEB_USER_ROLES = 'User'
265     NEW_EMAIL_USER_ROLES = 'User'
267 Tracker Schema
268 ==============
270 Note: if you modify the schema, you'll most likely need to edit the
271       `web interface`_ HTML template files and `detectors`_ to reflect
272       your changes.
274 A tracker schema defines what data is stored in the tracker's database.
275 Schemas are defined using Python code in the ``dbinit.py`` module of your
276 tracker. The "classic" schema looks like this (see below for the meaning
277 of ``'setkey'``)::
279     pri = Class(db, "priority", name=String(), order=String())
280     pri.setkey("name")
282     stat = Class(db, "status", name=String(), order=String())
283     stat.setkey("name")
285     keyword = Class(db, "keyword", name=String())
286     keyword.setkey("name")
288     user = Class(db, "user", username=String(), organisation=String(),
289         password=String(), address=String(), realname=String(),
290         phone=String())
291     user.setkey("username")
293     msg = FileClass(db, "msg", author=Link("user"), summary=String(),
294         date=Date(), recipients=Multilink("user"),
295         files=Multilink("file"))
297     file = FileClass(db, "file", name=String(), type=String())
299     issue = IssueClass(db, "issue", topic=Multilink("keyword"),
300         status=Link("status"), assignedto=Link("user"),
301         priority=Link("priority"))
302     issue.setkey('title')
304 Classes and Properties - creating a new information store
305 ---------------------------------------------------------
307 In the tracker above, we've defined 7 classes of information:
309   priority
310       Defines the possible levels of urgency for issues.
312   status
313       Defines the possible states of processing the issue may be in.
315   keyword
316       Initially empty, will hold keywords useful for searching issues.
318   user
319       Initially holding the "admin" user, will eventually have an entry
320       for all users using roundup.
322   msg
323       Initially empty, will hold all e-mail messages sent to or
324       generated by roundup.
326   file
327       Initially empty, will hold all files attached to issues.
329   issue
330       Initially empty, this is where the issue information is stored.
332 We define the "priority" and "status" classes to allow two things:
333 reduction in the amount of information stored on the issue and more
334 powerful, accurate searching of issues by priority and status. By only
335 requiring a link on the issue (which is stored as a single number) we
336 reduce the chance that someone mis-types a priority or status - or
337 simply makes a new one up.
340 Class and Items
341 ~~~~~~~~~~~~~~~
343 A Class defines a particular class (or type) of data that will be stored
344 in the database. A class comprises one or more properties, which gives
345 the information about the class items.
347 The actual data entered into the database, using ``class.create()``, are
348 called items. They have a special immutable property called ``'id'``. We
349 sometimes refer to this as the *itemid*.
352 Properties
353 ~~~~~~~~~~
355 A Class is comprised of one or more properties of the following types:
357 * String properties are for storing arbitrary-length strings.
358 * Password properties are for storing encoded arbitrary-length strings.
359   The default encoding is defined on the ``roundup.password.Password``
360   class.
361 * Date properties store date-and-time stamps. Their values are Timestamp
362   objects.
363 * Number properties store numeric values.
364 * Boolean properties store on/off, yes/no, true/false values.
365 * A Link property refers to a single other item selected from a
366   specified class. The class is part of the property; the value is an
367   integer, the id of the chosen item.
368 * A Multilink property refers to possibly many items in a specified
369   class. The value is a list of integers.
372 FileClass
373 ~~~~~~~~~
375 FileClasses save their "content" attribute off in a separate file from
376 the rest of the database. This reduces the number of large entries in
377 the database, which generally makes databases more efficient, and also
378 allows us to use command-line tools to operate on the files. They are
379 stored in the files sub-directory of the ``'db'`` directory in your
380 tracker.
383 IssueClass
384 ~~~~~~~~~~
386 IssueClasses automatically include the "messages", "files", "nosy", and
387 "superseder" properties.
389 The messages and files properties list the links to the messages and
390 files related to the issue. The nosy property is a list of links to
391 users who wish to be informed of changes to the issue - they get "CC'ed"
392 e-mails when messages are sent to or generated by the issue. The nosy
393 reactor (in the ``'detectors'`` directory) handles this action. The
394 superseder link indicates an issue which has superseded this one.
396 They also have the dynamically generated "creation", "activity" and
397 "creator" properties.
399 The value of the "creation" property is the date when an item was
400 created, and the value of the "activity" property is the date when any
401 property on the item was last edited (equivalently, these are the dates
402 on the first and last records in the item's journal). The "creator"
403 property holds a link to the user that created the issue.
406 setkey(property)
407 ~~~~~~~~~~~~~~~~
409 Select a String property of the class to be the key property. The key
410 property must be unique, and allows references to the items in the class
411 by the content of the key property. That is, we can refer to users by
412 their username: for example, let's say that there's an issue in roundup,
413 issue 23. There's also a user, richard, who happens to be user 2. To
414 assign an issue to him, we could do either of::
416      roundup-admin set issue23 assignedto=2
418 or::
420      roundup-admin set issue23 assignedto=richard
422 Note, the same thing can be done in the web and e-mail interfaces. 
424 If a class does not have an "order" property, the key is also used to
425 sort instances of the class when it is rendered in the user interface.
426 (If a class has no "order" property, sorting is by the labelproperty of
427 the class. This is computed, in order of precedence, as the key, the
428 "name", the "title", or the first property alphabetically.)
431 create(information)
432 ~~~~~~~~~~~~~~~~~~~
434 Create an item in the database. This is generally used to create items
435 in the "definitional" classes like "priority" and "status".
438 Examples of adding to your schema
439 ---------------------------------
441 TODO
444 Detectors - adding behaviour to your tracker
445 ============================================
446 .. _detectors:
448 Detectors are initialised every time you open your tracker database, so
449 you're free to add and remove them any time, even after the database is
450 initialised via the "roundup-admin initialise" command.
452 The detectors in your tracker fire *before* (**auditors**) and *after*
453 (**reactors**) changes to the contents of your database. They are Python
454 modules that sit in your tracker's ``detectors`` directory. You will
455 have some installed by default - have a look. You can write new
456 detectors or modify the existing ones. The existing detectors installed
457 for you are:
459 **nosyreaction.py**
460   This provides the automatic nosy list maintenance and email sending.
461   The nosy reactor (``nosyreaction``) fires when new messages are added
462   to issues. The nosy auditor (``updatenosy``) fires when issues are
463   changed, and figures out what changes need to be made to the nosy list
464   (such as adding new authors, etc.)
465 **statusauditor.py**
466   This provides the ``chatty`` auditor which changes the issue status
467   from ``unread`` or ``closed`` to ``chatting`` if new messages appear.
468   It also provides the ``presetunread`` auditor which pre-sets the
469   status to ``unread`` on new items if the status isn't explicitly
470   defined.
471 **messagesummary.py**
472   Generates the ``summary`` property for new messages based on the message
473   content.
474 **userauditor.py**
475   Verifies the content of some of the user fields (email addresses and
476   roles lists).
478 If you don't want this default behaviour, you're completely free to change
479 or remove these detectors.
481 See the detectors section in the `design document`__ for details of the
482 interface for detectors.
484 __ design.html
486 Sample additional detectors that have been found useful will appear in
487 the ``'detectors'`` directory of the Roundup distribution. If you want
488 to use one, copy it to the ``'detectors'`` of your tracker instance:
490 **newissuecopy.py**
491   This detector sends an email to a team address whenever a new issue is
492   created. The address is hard-coded into the detector, so edit it
493   before you use it (look for the text 'team@team.host') or you'll get
494   email errors!
496   The detector code::
498     from roundup import roundupdb
500     def newissuecopy(db, cl, nodeid, oldvalues):
501         ''' Copy a message about new issues to a team address.
502         '''
503         # so use all the messages in the create
504         change_note = cl.generateCreateNote(nodeid)
506         # send a copy to the nosy list
507         for msgid in cl.get(nodeid, 'messages'):
508             try:
509                 # note: last arg must be a list
510                 cl.send_message(nodeid, msgid, change_note,
511                     ['team@team.host'])
512             except roundupdb.MessageSendError, message:
513                 raise roundupdb.DetectorError, message
515     def init(db):
516         db.issue.react('create', newissuecopy)
519 Database Content
520 ================
522 Note: if you modify the content of definitional classes, you'll most
523        likely need to edit the tracker `detectors`_ to reflect your
524        changes.
526 Customisation of the special "definitional" classes (eg. status,
527 priority, resolution, ...) may be done either before or after the
528 tracker is initialised. The actual method of doing so is completely
529 different in each case though, so be careful to use the right one.
531 **Changing content before tracker initialisation**
532     Edit the dbinit module in your tracker to alter the items created in
533     using the ``create()`` methods.
535 **Changing content after tracker initialisation**
536     As the "admin" user, click on the "class list" link in the web
537     interface to bring up a list of all database classes. Click on the
538     name of the class you wish to change the content of.
540     You may also use the ``roundup-admin`` interface's create, set and
541     retire methods to add, alter or remove items from the classes in
542     question.
544 See "`adding a new field to the classic schema`_" for an example that
545 requires database content changes.
548 Access Controls
549 ===============
551 A set of Permissions is built into the security module by default:
553 - Edit (everything)
554 - View (everything)
556 The default interfaces define:
558 - Web Registration
559 - Web Access
560 - Web Roles
561 - Email Registration
562 - Email Access
564 These are hooked into the default Roles:
566 - Admin (Edit everything, View everything, Web Roles)
567 - User (Web Access, Email Access)
568 - Anonymous (Web Registration, Email Registration)
570 And finally, the "admin" user gets the "Admin" Role, and the "anonymous"
571 user gets "Anonymous" assigned when the database is initialised on
572 installation. The two default schemas then define:
574 - Edit issue, View issue (both)
575 - Edit file, View file (both)
576 - Edit msg, View msg (both)
577 - Edit support, View support (extended only)
579 and assign those Permissions to the "User" Role. Put together, these
580 settings appear in the ``open()`` function of the tracker ``dbinit.py``
581 (the following is taken from the "minimal" template's ``dbinit.py``)::
583     #
584     # SECURITY SETTINGS
585     #
586     # new permissions for this schema
587     for cl in ('user', ):
588         db.security.addPermission(name="Edit", klass=cl,
589             description="User is allowed to edit "+cl)
590         db.security.addPermission(name="View", klass=cl,
591             description="User is allowed to access "+cl)
593     # and give the regular users access to the web and email interface
594     p = db.security.getPermission('Web Access')
595     db.security.addPermissionToRole('User', p)
596     p = db.security.getPermission('Email Access')
597     db.security.addPermissionToRole('User', p)
599     # May users view other user information? Comment these lines out
600     # if you don't want them to
601     p = db.security.getPermission('View', 'user')
602     db.security.addPermissionToRole('User', p)
604     # Assign the appropriate permissions to the anonymous user's
605     # Anonymous role. Choices here are:
606     # - Allow anonymous users to register through the web
607     p = db.security.getPermission('Web Registration')
608     db.security.addPermissionToRole('Anonymous', p)
609     # - Allow anonymous (new) users to register through the email
610     #   gateway
611     p = db.security.getPermission('Email Registration')
612     db.security.addPermissionToRole('Anonymous', p)
615 New User Roles
616 --------------
618 New users are assigned the Roles defined in the config file as:
620 - NEW_WEB_USER_ROLES
621 - NEW_EMAIL_USER_ROLES
624 Changing Access Controls
625 ------------------------
627 You may alter the configuration variables to change the Role that new
628 web or email users get, for example to not give them access to the web
629 interface if they register through email. 
631 You may use the ``roundup-admin`` "``security``" command to display the
632 current Role and Permission configuration in your tracker.
635 Adding a new Permission
636 ~~~~~~~~~~~~~~~~~~~~~~~
638 When adding a new Permission, you will need to:
640 1. add it to your tracker's dbinit so it is created
641 2. enable it for the Roles that should have it (verify with
642    "``roundup-admin security``")
643 3. add it to the relevant HTML interface templates
644 4. add it to the appropriate xxxPermission methods on in your tracker
645    interfaces module
648 Example Scenarios
649 ~~~~~~~~~~~~~~~~~
651 **automatic registration of users in the e-mail gateway**
652  By giving the "anonymous" user the "Email Registration" Role, any
653  unidentified user will automatically be registered with the tracker
654  (with no password, so they won't be able to log in through the web
655  until an admin sets their password). Note: this is the default
656  behaviour in the tracker templates that ship with Roundup.
658 **anonymous access through the e-mail gateway**
659  Give the "anonymous" user the "Email Access" and ("Edit", "issue")
660  Roles but do not not give them the "Email Registration" Role. This
661  means that when an unknown user sends email into the tracker, they're
662  automatically logged in as "anonymous". Since they don't have the
663  "Email Registration" Role, they won't be automatically registered, but
664  since "anonymous" has permission to use the gateway, they'll still be
665  able to submit issues. Note that the Sender information - their email
666  address - will not be available - they're *anonymous*.
668 **only developers may be assigned issues**
669  Create a new Permission called "Fixer" for the "issue" class. Create a
670  new Role "Developer" which has that Permission, and assign that to the
671  appropriate users. Filter the list of users available in the assignedto
672  list to include only those users. Enforce the Permission with an
673  auditor. See the example 
674  `restricting the list of users that are assignable to a task`_.
676 **only managers may sign off issues as complete**
677  Create a new Permission called "Closer" for the "issue" class. Create a
678  new Role "Manager" which has that Permission, and assign that to the
679  appropriate users. In your web interface, only display the "resolved"
680  issue state option when the user has the "Closer" Permissions. Enforce
681  the Permission with an auditor. This is very similar to the previous
682  example, except that the web interface check would look like::
684    <option tal:condition="python:request.user.hasPermission('Closer')"
685            value="resolved">Resolved</option>
686  
687 **don't give web access to users who register through email**
688  Create a new Role called "Email User" which has all the Permissions of
689  the normal "User" Role minus the "Web Access" Permission. This will
690  allow users to send in emails to the tracker, but not access the web
691  interface.
693 **let some users edit the details of all users**
694  Create a new Role called "User Admin" which has the Permission for
695  editing users::
697     db.security.addRole(name='User Admin', description='Managing users')
698     p = db.security.getPermission('Edit', 'user')
699     db.security.addPermissionToRole('User Admin', p)
701  and assign the Role to the users who need the permission.
704 Web Interface
705 =============
707 .. contents::
708    :local:
709    :depth: 1
711 The web interface is provided by the ``roundup.cgi.client`` module and
712 is used by ``roundup.cgi``, ``roundup-server`` and ``ZRoundup``
713 (``ZRoundup``  is broken, until further notice). In all cases, we
714 determine which tracker is being accessed (the first part of the URL
715 path inside the scope of the CGI handler) and pass control on to the
716 tracker ``interfaces.Client`` class - which uses the ``Client`` class
717 from ``roundup.cgi.client`` - which handles the rest of the access
718 through its ``main()`` method. This means that you can do pretty much
719 anything you want as a web interface to your tracker.
721 Repercussions of changing the tracker schema
722 ---------------------------------------------
724 If you choose to change the `tracker schema`_ you will need to ensure
725 the web interface knows about it:
727 1. Index, item and search pages for the relevant classes may need to
728    have properties added or removed,
729 2. The "page" template may require links to be changed, as might the
730    "home" page's content arguments.
732 How requests are processed
733 --------------------------
735 The basic processing of a web request proceeds as follows:
737 1. figure out who we are, defaulting to the "anonymous" user
738 2. figure out what the request is for - we call this the "context"
739 3. handle any requested action (item edit, search, ...)
740 4. render the template requested by the context, resulting in HTML
741    output
743 In some situations, exceptions occur:
745 - HTTP Redirect  (generally raised by an action)
746 - SendFile       (generally raised by ``determine_context``)
747     here we serve up a FileClass "content" property
748 - SendStaticFile (generally raised by ``determine_context``)
749     here we serve up a file from the tracker "html" directory
750 - Unauthorised   (generally raised by an action)
751     here the action is cancelled, the request is rendered and an error
752     message is displayed indicating that permission was not granted for
753     the action to take place
754 - NotFound       (raised wherever it needs to be)
755     this exception percolates up to the CGI interface that called the
756     client
758 Determining web context
759 -----------------------
761 To determine the "context" of a request, we look at the URL and the
762 special request variable ``@template``. The URL path after the tracker
763 identifier is examined. Typical URL paths look like:
765 1.  ``/tracker/issue``
766 2.  ``/tracker/issue1``
767 3.  ``/tracker/_file/style.css``
768 4.  ``/cgi-bin/roundup.cgi/tracker/file1``
769 5.  ``/cgi-bin/roundup.cgi/tracker/file1/kitten.png``
771 where the "tracker identifier" is "tracker" in the above cases. That means
772 we're looking at "issue", "issue1", "_file/style.css", "file1" and
773 "file1/kitten.png" in the cases above. The path is generally only one
774 entry long - longer paths are handled differently.
776 a. if there is no path, then we are in the "home" context.
777 b. if the path starts with "_file" (as in example 3,
778    "/tracker/_file/style.css"), then the additional path entry,
779    "style.css" specifies the filename of a static file we're to serve up
780    from the tracker "html" directory. Raises a SendStaticFile exception.
781 c. if there is something in the path (as in example 1, "issue"), it
782    identifies the tracker class we're to display.
783 d. if the path is an item designator (as in examples 2 and 4, "issue1"
784    and "file1"), then we're to display a specific item.
785 e. if the path starts with an item designator and is longer than one
786    entry (as in example 5, "file1/kitten.png"), then we're assumed to be
787    handling an item of a ``FileClass``, and the extra path information
788    gives the filename that the client is going to label the download
789    with (i.e. "file1/kitten.png" is nicer to download than "file1").
790    This raises a ``SendFile`` exception.
792 Both b. and e. stop before we bother to determine the template we're
793 going to use. That's because they don't actually use templates.
795 The template used is specified by the ``@template`` CGI variable, which
796 defaults to:
798 - only classname suplied:        "index"
799 - full item designator supplied: "item"
802 Performing actions in web requests
803 ----------------------------------
805 When a user requests a web page, they may optionally also request for an
806 action to take place. As described in `how requests are processed`_, the
807 action is performed before the requested page is generated. Actions are
808 triggered by using a ``@action`` CGI variable, where the value is one
809 of:
811 **login**
812  Attempt to log a user in.
814 **logout**
815  Log the user out - make them "anonymous".
817 **register**
818  Attempt to create a new user based on the contents of the form and then
819  log them in.
821 **edit**
822  Perform an edit of an item in the database. There are some `special form
823  variables`_ you may use.
825 **new**
826  Add a new item to the database. You may use the same `special form
827  variables`_ as in the "edit" action.
829 **retire**
830  Retire the item in the database.
832 **editCSV**
833  Performs an edit of all of a class' items in one go. See also the
834  *class*.csv templating method which generates the CSV data to be
835  edited, and the ``'_generic.index'`` template which uses both of these
836  features.
838 **search**
839  Mangle some of the form variables:
841  - Set the form ":filter" variable based on the values of the filter
842    variables - if they're set to anything other than "dontcare" then add
843    them to :filter.
845  - Also handle the ":queryname" variable and save off the query to the
846    user's query list.
848 Each of the actions is implemented by a corresponding ``*actionAction*``
849 (where "action" is the name of the action) method on the
850 ``roundup.cgi.Client`` class, which also happens to be available in your
851 tracker instance as ``interfaces.Client``. So if you need to define new
852 actions, you may add them there (see `defining new web actions`_).
854 Each action also has a corresponding ``*actionPermission*`` (where
855 "action" is the name of the action) method which determines whether the
856 action is permissible given the current user. The base permission checks
857 are:
859 **login**
860  Determine whether the user has permission to log in. Base behaviour is
861  to check the user has "Web Access".
862 **logout**
863  No permission checks are made.
864 **register**
865  Determine whether the user has permission to register. Base behaviour
866  is to check the user has the "Web Registration" Permission.
867 **edit**
868  Determine whether the user has permission to edit this item. Base
869  behaviour is to check whether the user can edit this class. If we're
870  editing the "user" class, users are allowed to edit their own details -
871  unless they try to edit the "roles" property, which requires the
872  special Permission "Web Roles".
873 **new**
874  Determine whether the user has permission to create (or edit) this
875  item. Base behaviour is to check the user can edit this class. No
876  additional property checks are made. Additionally, new user items may
877  be created if the user has the "Web Registration" Permission.
878 **editCSV**
879  Determine whether the user has permission to edit this class. Base
880  behaviour is to check whether the user may edit this class.
881 **search**
882  Determine whether the user has permission to search this class. Base
883  behaviour is to check whether the user may view this class.
886 Special form variables
887 ----------------------
889 Item properties and their values are edited with html FORM
890 variables and their values. You can:
892 - Change the value of some property of the current item.
893 - Create a new item of any class, and edit the new item's
894   properties,
895 - Attach newly created items to a multilink property of the
896   current item.
897 - Remove items from a multilink property of the current item.
898 - Specify that some properties are required for the edit
899   operation to be successful.
901 In the following, <bracketed> values are variable, "@" may be
902 either ":" or "@", and other text "required" is fixed.
904 Most properties are specified as form variables:
906 ``<propname>``
907   property on the current context item
909 ``<designator>"@"<propname>``
910   property on the indicated item (for editing related information)
912 Designators name a specific item of a class.
914 ``<classname><N>``
915     Name an existing item of class <classname>.
917 ``<classname>"-"<N>``
918     Name the <N>th new item of class <classname>. If the form
919     submission is successful, a new item of <classname> is
920     created. Within the submitted form, a particular
921     designator of this form always refers to the same new
922     item.
924 Once we have determined the "propname", we look at it to see
925 if it's special:
927 ``@required``
928     The associated form value is a comma-separated list of
929     property names that must be specified when the form is
930     submitted for the edit operation to succeed.  
932     When the <designator> is missing, the properties are
933     for the current context item.  When <designator> is
934     present, they are for the item specified by
935     <designator>.
937     The "@required" specifier must come before any of the
938     properties it refers to are assigned in the form.
940 ``@remove@<propname>=id(s)`` or ``@add@<propname>=id(s)``
941     The "@add@" and "@remove@" edit actions apply only to
942     Multilink properties.  The form value must be a
943     comma-separate list of keys for the class specified by
944     the simple form variable.  The listed items are added
945     to (respectively, removed from) the specified
946     property.
948 ``@link@<propname>=<designator>``
949     If the edit action is "@link@", the simple form
950     variable must specify a Link or Multilink property.
951     The form value is a comma-separated list of
952     designators.  The item corresponding to each
953     designator is linked to the property given by simple
954     form variable.
956 None of the above (ie. just a simple form value)
957     The value of the form variable is converted
958     appropriately, depending on the type of the property.
960     For a Link('klass') property, the form value is a
961     single key for 'klass', where the key field is
962     specified in dbinit.py.  
964     For a Multilink('klass') property, the form value is a
965     comma-separated list of keys for 'klass', where the
966     key field is specified in dbinit.py.  
968     Note that for simple-form-variables specifiying Link
969     and Multilink properties, the linked-to class must
970     have a key field.
972     For a String() property specifying a filename, the
973     file named by the form value is uploaded. This means we
974     try to set additional properties "filename" and "type" (if
975     they are valid for the class).  Otherwise, the property
976     is set to the form value.
978     For Date(), Interval(), Boolean(), and Number()
979     properties, the form value is converted to the
980     appropriate
982 Any of the form variables may be prefixed with a classname or
983 designator.
985 Two special form values are supported for backwards compatibility:
987 @note
988     This is equivalent to::
990         @link@messages=msg-1
991         @msg-1@content=value
993     except that in addition, the "author" and "date" properties of
994     "msg-1" are set to the userid of the submitter, and the current
995     time, respectively.
997 @file
998     This is equivalent to::
1000         @link@files=file-1
1001         @file-1@content=value
1003     The String content value is handled as described above for file
1004     uploads.
1006 If both the "@note" and "@file" form variables are
1007 specified, the action::
1009         @link@msg-1@files=file-1
1011 is also performed.
1013 We also check that FileClass items have a "content" property with
1014 actual content, otherwise we remove them from all_props before
1015 returning.
1019 Default templates
1020 -----------------
1022 Most customisation of the web view can be done by modifying the
1023 templates in the tracker ``'html'`` directory. There are several types
1024 of files in there. The *minimal* template includes:
1026 **page.html**
1027   This template usually defines the overall look of your tracker. When
1028   you view an issue, it appears inside this template. When you view an
1029   index, it also appears inside this template. This template defines a
1030   macro called "icing" which is used by almost all other templates as a
1031   coating for their content, using its "content" slot. It also defines
1032   the "head_title" and "body_title" slots to allow setting of the page
1033   title.
1034 **home.html**
1035   the default page displayed when no other page is indicated by the user
1036 **home.classlist.html**
1037   a special version of the default page that lists the classes in the
1038   tracker
1039 **classname.item.html**
1040   displays an item of the *classname* class
1041 **classname.index.html**
1042   displays a list of *classname* items
1043 **classname.search.html**
1044   displays a search page for *classname* items
1045 **_generic.index.html**
1046   used to display a list of items where there is no
1047   ``*classname*.index`` available
1048 **_generic.help.html**
1049   used to display a "class help" page where there is no
1050   ``*classname*.help``
1051 **user.register.html**
1052   a special page just for the user class, that renders the registration
1053   page
1054 **style.css.html**
1055   a static file that is served up as-is
1057 The *classic* template has a number of additional templates.
1059 Note: Remember that you can create any template extension you want to,
1060 so if you just want to play around with the templating for new issues,
1061 you can copy the current "issue.item" template to "issue.test", and then
1062 access the test template using the "@template" URL argument::
1064    http://your.tracker.example/tracker/issue?@template=test
1066 and it won't affect your users using the "issue.item" template.
1069 How the templates work
1070 ----------------------
1073 Basic Templating Actions
1074 ~~~~~~~~~~~~~~~~~~~~~~~~
1076 Roundup's templates consist of special attributes on the HTML tags.
1077 These attributes form the Template Attribute Language, or TAL. The basic
1078 TAL commands are:
1080 **tal:define="variable expression; variable expression; ..."**
1081    Define a new variable that is local to this tag and its contents. For
1082    example::
1084       <html tal:define="title request/description">
1085        <head><title tal:content="title"></title></head>
1086       </html>
1088    In this example, the variable "title" is defined as the result of the
1089    expression "request/description". The "tal:content" command inside the
1090    <html> tag may then use the "title" variable.
1092 **tal:condition="expression"**
1093    Only keep this tag and its contents if the expression is true. For
1094    example::
1096      <p tal:condition="python:request.user.hasPermission('View', 'issue')">
1097       Display some issue information.
1098      </p>
1100    In the example, the <p> tag and its contents are only displayed if
1101    the user has the "View" permission for issues. We consider the number
1102    zero, a blank string, an empty list, and the built-in variable
1103    nothing to be false values. Nearly every other value is true,
1104    including non-zero numbers, and strings with anything in them (even
1105    spaces!).
1107 **tal:repeat="variable expression"**
1108    Repeat this tag and its contents for each element of the sequence
1109    that the expression returns, defining a new local variable and a
1110    special "repeat" variable for each element. For example::
1112      <tr tal:repeat="u user/list">
1113       <td tal:content="u/id"></td>
1114       <td tal:content="u/username"></td>
1115       <td tal:content="u/realname"></td>
1116      </tr>
1118    The example would iterate over the sequence of users returned by
1119    "user/list" and define the local variable "u" for each entry.
1121 **tal:replace="expression"**
1122    Replace this tag with the result of the expression. For example::
1124     <span tal:replace="request/user/realname" />
1126    The example would replace the <span> tag and its contents with the
1127    user's realname. If the user's realname was "Bruce", then the
1128    resultant output would be "Bruce".
1130 **tal:content="expression"**
1131    Replace the contents of this tag with the result of the expression.
1132    For example::
1134     <span tal:content="request/user/realname">user's name appears here
1135     </span>
1137    The example would replace the contents of the <span> tag with the
1138    user's realname. If the user's realname was "Bruce" then the
1139    resultant output would be "<span>Bruce</span>".
1141 **tal:attributes="attribute expression; attribute expression; ..."**
1142    Set attributes on this tag to the results of expressions. For
1143    example::
1145      <a tal:attributes="href string:user${request/user/id}">My Details</a>
1147    In the example, the "href" attribute of the <a> tag is set to the
1148    value of the "string:user${request/user/id}" expression, which will
1149    be something like "user123".
1151 **tal:omit-tag="expression"**
1152    Remove this tag (but not its contents) if the expression is true. For
1153    example::
1155       <span tal:omit-tag="python:1">Hello, world!</span>
1157    would result in output of::
1159       Hello, world!
1161 Note that the commands on a given tag are evaulated in the order above,
1162 so *define* comes before *condition*, and so on.
1164 Additionally, you may include tags such as <tal:block>, which are
1165 removed from output. Its content is kept, but the tag itself is not (so
1166 don't go using any "tal:attributes" commands on it). This is useful for
1167 making arbitrary blocks of HTML conditional or repeatable (very handy
1168 for repeating multiple table rows, which would othewise require an
1169 illegal tag placement to effect the repeat).
1172 Templating Expressions
1173 ~~~~~~~~~~~~~~~~~~~~~~
1175 The expressions you may use in the attribute values may be one of the
1176 following forms:
1178 **Path Expressions** - eg. ``item/status/checklist``
1179    These are object attribute / item accesses. Roughly speaking, the
1180    path ``item/status/checklist`` is broken into parts ``item``,
1181    ``status`` and ``checklist``. The ``item`` part is the root of the
1182    expression. We then look for a ``status`` attribute on ``item``, or
1183    failing that, a ``status`` item (as in ``item['status']``). If that
1184    fails, the path expression fails. When we get to the end, the object
1185    we're left with is evaluated to get a string - if it is a method, it
1186    is called; if it is an object, it is stringified. Path expressions
1187    may have an optional ``path:`` prefix, but they are the default
1188    expression type, so it's not necessary.
1190    If an expression evaluates to ``default``, then the expression is
1191    "cancelled" - whatever HTML already exists in the template will
1192    remain (tag content in the case of ``tal:content``, attributes in the
1193    case of ``tal:attributes``).
1195    If an expression evaluates to ``nothing`` then the target of the
1196    expression is removed (tag content in the case of ``tal:content``,
1197    attributes in the case of ``tal:attributes`` and the tag itself in
1198    the case of ``tal:replace``).
1200    If an element in the path may not exist, then you can use the ``|``
1201    operator in the expression to provide an alternative. So, the
1202    expression ``request/form/foo/value | default`` would simply leave
1203    the current HTML in place if the "foo" form variable doesn't exist.
1205    You may use the python function ``path``, as in
1206    ``path("item/status")``, to embed path expressions in Python
1207    expressions.
1209 **String Expressions** - eg. ``string:hello ${user/name}`` 
1210    These expressions are simple string interpolations - though they can
1211    be just plain strings with no interpolation if you want. The
1212    expression in the ``${ ... }`` is just a path expression as above.
1214 **Python Expressions** - eg. ``python: 1+1`` 
1215    These expressions give the full power of Python. All the "root level"
1216    variables are available, so ``python:item.status.checklist()`` would
1217    be equivalent to ``item/status/checklist``, assuming that
1218    ``checklist`` is a method.
1220 Modifiers:
1222 **structure** - eg. ``structure python:msg.content.plain(hyperlink=1)``
1223    The result of expressions are normally *escaped* to be safe for HTML
1224    display (all "<", ">" and "&" are turned into special entities). The
1225    ``structure`` expression modifier turns off this escaping - the
1226    result of the expression is now assumed to be HTML, which is passed
1227    to the web browser for rendering.
1229 **not:** - eg. ``not:python:1=1``
1230    This simply inverts the logical true/false value of another
1231    expression.
1234 Template Macros
1235 ~~~~~~~~~~~~~~~
1237 Macros are used in Roundup to save us from repeating the same common
1238 page stuctures over and over. The most common (and probably only) macro
1239 you'll use is the "icing" macro defined in the "page" template.
1241 Macros are generated and used inside your templates using special
1242 attributes similar to the `basic templating actions`_. In this case,
1243 though, the attributes belong to the Macro Expansion Template Attribute
1244 Language, or METAL. The macro commands are:
1246 **metal:define-macro="macro name"**
1247   Define that the tag and its contents are now a macro that may be
1248   inserted into other templates using the *use-macro* command. For
1249   example::
1251     <html metal:define-macro="page">
1252      ...
1253     </html>
1255   defines a macro called "page" using the ``<html>`` tag and its
1256   contents. Once defined, macros are stored on the template they're
1257   defined on in the ``macros`` attribute. You can access them later on
1258   through the ``templates`` variable, eg. the most common
1259   ``templates/page/macros/icing`` to access the "page" macro of the
1260   "page" template.
1262 **metal:use-macro="path expression"**
1263   Use a macro, which is identified by the path expression (see above).
1264   This will replace the current tag with the identified macro contents.
1265   For example::
1267    <tal:block metal:use-macro="templates/page/macros/icing">
1268     ...
1269    </tal:block>
1271    will replace the tag and its contents with the "page" macro of the
1272    "page" template.
1274 **metal:define-slot="slot name"** and **metal:fill-slot="slot name"**
1275   To define *dynamic* parts of the macro, you define "slots" which may
1276   be filled when the macro is used with a *use-macro* command. For
1277   example, the ``templates/page/macros/icing`` macro defines a slot like
1278   so::
1280     <title metal:define-slot="head_title">title goes here</title>
1282   In your *use-macro* command, you may now use a *fill-slot* command
1283   like this::
1285     <title metal:fill-slot="head_title">My Title</title>
1287   where the tag that fills the slot completely replaces the one defined
1288   as the slot in the macro.
1290 Note that you may not mix METAL and TAL commands on the same tag, but
1291 TAL commands may be used freely inside METAL-using tags (so your
1292 *fill-slots* tags may have all manner of TAL inside them).
1295 Information available to templates
1296 ----------------------------------
1298 Note: this is implemented by
1299 ``roundup.cgi.templating.RoundupPageTemplate``
1301 The following variables are available to templates.
1303 **context**
1304   The current context. This is either None, a `hyperdb class wrapper`_
1305   or a `hyperdb item wrapper`_
1306 **request**
1307   Includes information about the current request, including:
1308    - the current index information (``filterspec``, ``filter`` args,
1309      ``properties``, etc) parsed out of the form. 
1310    - methods for easy filterspec link generation
1311    - *user*, the current user item as an HTMLItem instance
1312    - *form*
1313      The current CGI form information as a mapping of form argument name
1314      to value
1315 **config**
1316   This variable holds all the values defined in the tracker config.py
1317   file (eg. TRACKER_NAME, etc.)
1318 **db**
1319   The current database, used to access arbitrary database items.
1320 **templates**
1321   Access to all the tracker templates by name. Used mainly in
1322   *use-macro* commands.
1323 **utils**
1324   This variable makes available some utility functions like batching.
1325 **nothing**
1326   This is a special variable - if an expression evaluates to this, then
1327   the tag (in the case of a ``tal:replace``), its contents (in the case
1328   of ``tal:content``) or some attributes (in the case of
1329   ``tal:attributes``) will not appear in the the output. So, for
1330   example::
1332     <span tal:attributes="class nothing">Hello, World!</span>
1334   would result in::
1336     <span>Hello, World!</span>
1338 **default**
1339   Also a special variable - if an expression evaluates to this, then the
1340   existing HTML in the template will not be replaced or removed, it will
1341   remain. So::
1343     <span tal:replace="default">Hello, World!</span>
1345   would result in::
1347     <span>Hello, World!</span>
1350 The context variable
1351 ~~~~~~~~~~~~~~~~~~~~
1353 The *context* variable is one of three things based on the current
1354 context (see `determining web context`_ for how we figure this out):
1356 1. if we're looking at a "home" page, then it's None
1357 2. if we're looking at a specific hyperdb class, it's a
1358    `hyperdb class wrapper`_.
1359 3. if we're looking at a specific hyperdb item, it's a
1360    `hyperdb item wrapper`_.
1362 If the context is not None, we can access the properties of the class or
1363 item. The only real difference between cases 2 and 3 above are:
1365 1. the properties may have a real value behind them, and this will
1366    appear if the property is displayed through ``context/property`` or
1367    ``context/property/field``.
1368 2. the context's "id" property will be a false value in the second case,
1369    but a real, or true value in the third. Thus we can determine whether
1370    we're looking at a real item from the hyperdb by testing
1371    "context/id".
1373 Hyperdb class wrapper
1374 :::::::::::::::::::::
1376 Note: this is implemented by the ``roundup.cgi.templating.HTMLClass``
1377 class.
1379 This wrapper object provides access to a hyperb class. It is used
1380 primarily in both index view and new item views, but it's also usable
1381 anywhere else that you wish to access information about a class, or the
1382 items of a class, when you don't have a specific item of that class in
1383 mind.
1385 We allow access to properties. There will be no "id" property. The value
1386 accessed through the property will be the current value of the same name
1387 from the CGI form.
1389 There are several methods available on these wrapper objects:
1391 =========== =============================================================
1392 Method      Description
1393 =========== =============================================================
1394 properties  return a `hyperdb property wrapper`_ for all of this class's
1395             properties.
1396 list        lists all of the active (not retired) items in the class.
1397 csv         return the items of this class as a chunk of CSV text.
1398 propnames   lists the names of the properties of this class.
1399 filter      lists of items from this class, filtered and sorted by the
1400             current *request* filterspec/filter/sort/group args
1401 classhelp   display a link to a javascript popup containing this class'
1402             "help" template.
1403 submit      generate a submit button (and action hidden element)
1404 renderWith  render this class with the given template.
1405 history     returns 'New node - no history' :)
1406 is_edit_ok  is the user allowed to Edit the current class?
1407 is_view_ok  is the user allowed to View the current class?
1408 =========== =============================================================
1410 Note that if you have a property of the same name as one of the above
1411 methods, you'll need to access it using a python "item access"
1412 expression. For example::
1414    python:context['list']
1416 will access the "list" property, rather than the list method.
1419 Hyperdb item wrapper
1420 ::::::::::::::::::::
1422 Note: this is implemented by the ``roundup.cgi.templating.HTMLItem``
1423 class.
1425 This wrapper object provides access to a hyperb item.
1427 We allow access to properties. There will be no "id" property. The value
1428 accessed through the property will be the current value of the same name
1429 from the CGI form.
1431 There are several methods available on these wrapper objects:
1433 =============== ========================================================
1434 Method          Description
1435 =============== ========================================================
1436 submit          generate a submit button (and action hidden element)
1437 journal         return the journal of the current item (**not
1438                 implemented**)
1439 history         render the journal of the current item as HTML
1440 renderQueryForm specific to the "query" class - render the search form
1441                 for the query
1442 hasPermission   specific to the "user" class - determine whether the
1443                 user has a Permission
1444 is_edit_ok      is the user allowed to Edit the current item?
1445 is_view_ok      is the user allowed to View the current item?
1446 =============== ========================================================
1448 Note that if you have a property of the same name as one of the above
1449 methods, you'll need to access it using a python "item access"
1450 expression. For example::
1452    python:context['journal']
1454 will access the "journal" property, rather than the journal method.
1457 Hyperdb property wrapper
1458 ::::::::::::::::::::::::
1460 Note: this is implemented by subclasses of the
1461 ``roundup.cgi.templating.HTMLProperty`` class (``HTMLStringProperty``,
1462 ``HTMLNumberProperty``, and so on).
1464 This wrapper object provides access to a single property of a class. Its
1465 value may be either:
1467 1. if accessed through a `hyperdb item wrapper`_, then it's a value from
1468    the hyperdb
1469 2. if access through a `hyperdb class wrapper`_, then it's a value from
1470    the CGI form
1473 The property wrapper has some useful attributes:
1475 =============== ========================================================
1476 Attribute       Description
1477 =============== ========================================================
1478 _name           the name of the property
1479 _value          the value of the property if any - this is the actual
1480                 value retrieved from the hyperdb for this property
1481 =============== ========================================================
1483 There are several methods available on these wrapper objects:
1485 =========== ================================================================
1486 Method      Description
1487 =========== ================================================================
1488 plain       render a "plain" representation of the property. This method
1489             may take two arguments:
1491             escape
1492              If true, escape the text so it is HTML safe (default: no). The
1493              reason this defaults to off is that text is usually escaped
1494              at a later stage by the TAL commands, unless the "structure"
1495              option is used in the template. The following ``tal:content``
1496              expressions are all equivalent::
1497  
1498               "structure python:msg.content.plain(escape=1)"
1499               "python:msg.content.plain()"
1500               "msg/content/plain"
1501               "msg/content"
1503              Usually you'll only want to use the escape option in a
1504              complex expression.
1506             hyperlink
1507              If true, turn URLs, email addresses and hyperdb item
1508              designators in the text into hyperlinks (default: no). Note
1509              that you'll need to use the "structure" TAL option if you
1510              want to use this ``tal:content`` expression::
1511   
1512               "structure python:msg.content.plain(hyperlink=1)"
1514              Note also that the text is automatically HTML-escaped before
1515              the hyperlinking transformation.
1516 hyperlinked The same as msg.content.plain(hyperlink=1), but nicer::
1518               "structure msg/content/hyperlinked"
1520 field       render an appropriate form edit field for the property - for
1521             most types this is a text entry box, but for Booleans it's a
1522             tri-state yes/no/neither selection.
1523 stext       only on String properties - render the value of the property
1524             as StructuredText (requires the StructureText module to be
1525             installed separately)
1526 multiline   only on String properties - render a multiline form edit
1527             field for the property
1528 email       only on String properties - render the value of the property
1529             as an obscured email address
1530 confirm     only on Password properties - render a second form edit field
1531             for the property, used for confirmation that the user typed
1532             the password correctly. Generates a field with name
1533             "name:confirm".
1534 now         only on Date properties - return the current date as a new
1535             property
1536 reldate     only on Date properties - render the interval between the date
1537             and now
1538 local       only on Date properties - return this date as a new property
1539             with some timezone offset
1540 pretty      only on Interval properties - render the interval in a pretty
1541             format (eg. "yesterday")
1542 menu        only on Link and Multilink properties - render a form select
1543             list for this property
1544 reverse     only on Multilink properties - produce a list of the linked
1545             items in reverse order
1546 =========== ================================================================
1549 The request variable
1550 ~~~~~~~~~~~~~~~~~~~~
1552 Note: this is implemented by the ``roundup.cgi.templating.HTMLRequest``
1553 class.
1555 The request variable is packed with information about the current
1556 request.
1558 .. taken from ``roundup.cgi.templating.HTMLRequest`` docstring
1560 =========== ============================================================
1561 Variable    Holds
1562 =========== ============================================================
1563 form        the CGI form as a cgi.FieldStorage
1564 env         the CGI environment variables
1565 base        the base URL for this tracker
1566 user        a HTMLUser instance for this user
1567 classname   the current classname (possibly None)
1568 template    the current template (suffix, also possibly None)
1569 form        the current CGI form variables in a FieldStorage
1570 =========== ============================================================
1572 **Index page specific variables (indexing arguments)**
1574 =========== ============================================================
1575 Variable    Holds
1576 =========== ============================================================
1577 columns     dictionary of the columns to display in an index page
1578 show        a convenience access to columns - request/show/colname will
1579             be true if the columns should be displayed, false otherwise
1580 sort        index sort column (direction, column name)
1581 group       index grouping property (direction, column name)
1582 filter      properties to filter the index on
1583 filterspec  values to filter the index on
1584 search_text text to perform a full-text search on for an index
1585 =========== ============================================================
1587 There are several methods available on the request variable:
1589 =============== ========================================================
1590 Method          Description
1591 =============== ========================================================
1592 description     render a description of the request - handle for the
1593                 page title
1594 indexargs_form  render the current index args as form elements
1595 indexargs_url   render the current index args as a URL
1596 base_javascript render some javascript that is used by other components
1597                 of the templating
1598 batch           run the current index args through a filter and return a
1599                 list of items (see `hyperdb item wrapper`_, and
1600                 `batching`_)
1601 =============== ========================================================
1603 The form variable
1604 :::::::::::::::::
1606 The form variable is a bit special because it's actually a python
1607 FieldStorage object. That means that you have two ways to access its
1608 contents. For example, to look up the CGI form value for the variable
1609 "name", use the path expression::
1611    request/form/name/value
1613 or the python expression::
1615    python:request.form['name'].value
1617 Note the "item" access used in the python case, and also note the
1618 explicit "value" attribute we have to access. That's because the form
1619 variables are stored as MiniFieldStorages. If there's more than one
1620 "name" value in the form, then the above will break since
1621 ``request/form/name`` is actually a *list* of MiniFieldStorages. So it's
1622 best to know beforehand what you're dealing with.
1625 The db variable
1626 ~~~~~~~~~~~~~~~
1628 Note: this is implemented by the ``roundup.cgi.templating.HTMLDatabase``
1629 class.
1631 Allows access to all hyperdb classes as attributes of this variable. If
1632 you want access to the "user" class, for example, you would use::
1634   db/user
1635   python:db.user
1637 Also, the current id of the current user is available as
1638 ``db.getuid()``. This isn't so useful in templates (where you have
1639 ``request/user``), but it can be useful in detectors or interfaces.
1641 The access results in a `hyperdb class wrapper`_.
1644 The templates variable
1645 ~~~~~~~~~~~~~~~~~~~~~~
1647 Note: this is implemented by the ``roundup.cgi.templating.Templates``
1648 class.
1650 This variable doesn't have any useful methods defined. It supports being
1651 used in expressions to access the templates, and consequently the
1652 template macros. You may access the templates using the following path
1653 expression::
1655    templates/name
1657 or the python expression::
1659    templates[name]
1661 where "name" is the name of the template you wish to access. The
1662 template has one useful attribute, namely "macros". To access a specific
1663 macro (called "macro_name"), use the path expression::
1665    templates/name/macros/macro_name
1667 or the python expression::
1669    templates[name].macros[macro_name]
1672 The utils variable
1673 ~~~~~~~~~~~~~~~~~~
1675 Note: this is implemented by the
1676 ``roundup.cgi.templating.TemplatingUtils`` class, but it may be extended
1677 as described below.
1679 =============== ========================================================
1680 Method          Description
1681 =============== ========================================================
1682 Batch           return a batch object using the supplied list
1683 =============== ========================================================
1685 You may add additional utility methods by writing them in your tracker
1686 ``interfaces.py`` module's ``TemplatingUtils`` class. See `adding a time
1687 log to your issues`_ for an example. The TemplatingUtils class itself
1688 will have a single attribute, ``client``, which may be used to access
1689 the ``client.db`` when you need to perform arbitrary database queries.
1691 Batching
1692 ::::::::
1694 Use Batch to turn a list of items, or item ids of a given class, into a
1695 series of batches. Its usage is::
1697     python:utils.Batch(sequence, size, start, end=0, orphan=0,
1698     overlap=0)
1700 or, to get the current index batch::
1702     request/batch
1704 The parameters are:
1706 ========= ==============================================================
1707 Parameter  Usage
1708 ========= ==============================================================
1709 sequence  a list of HTMLItems
1710 size      how big to make the sequence.
1711 start     where to start (0-indexed) in the sequence.
1712 end       where to end (0-indexed) in the sequence.
1713 orphan    if the next batch would contain less items than this value,
1714           then it is combined with this batch
1715 overlap   the number of items shared between adjacent batches
1716 ========= ==============================================================
1718 All of the parameters are assigned as attributes on the batch object. In
1719 addition, it has several more attributes:
1721 =============== ========================================================
1722 Attribute       Description
1723 =============== ========================================================
1724 start           indicates the start index of the batch. *Note: unlike
1725                 the argument, is a 1-based index (I know, lame)*
1726 first           indicates the start index of the batch *as a 0-based
1727                 index*
1728 length          the actual number of elements in the batch
1729 sequence_length the length of the original, unbatched, sequence.
1730 =============== ========================================================
1732 And several methods:
1734 =============== ========================================================
1735 Method          Description
1736 =============== ========================================================
1737 previous        returns a new Batch with the previous batch settings
1738 next            returns a new Batch with the next batch settings
1739 propchanged     detect if the named property changed on the current item
1740                 when compared to the last item
1741 =============== ========================================================
1743 An example of batching::
1745  <table class="otherinfo">
1746   <tr><th colspan="4" class="header">Existing Keywords</th></tr>
1747   <tr tal:define="keywords db/keyword/list"
1748       tal:repeat="start python:range(0, len(keywords), 4)">
1749    <td tal:define="batch python:utils.Batch(keywords, 4, start)"
1750        tal:repeat="keyword batch" tal:content="keyword/name">
1751        keyword here</td>
1752   </tr>
1753  </table>
1755 ... which will produce a table with four columns containing the items of
1756 the "keyword" class (well, their "name" anyway).
1758 Displaying Properties
1759 ---------------------
1761 Properties appear in the user interface in three contexts: in indices,
1762 in editors, and as search arguments. For each type of property, there
1763 are several display possibilities. For example, in an index view, a
1764 string property may just be printed as a plain string, but in an editor
1765 view, that property may be displayed in an editable field.
1768 Index Views
1769 -----------
1771 This is one of the class context views. It is also the default view for
1772 classes. The template used is "*classname*.index".
1775 Index View Specifiers
1776 ~~~~~~~~~~~~~~~~~~~~~
1778 An index view specifier (URL fragment) looks like this (whitespace has
1779 been added for clarity)::
1781      /issue?status=unread,in-progress,resolved&
1782             topic=security,ui&
1783             :group=+priority&
1784             :sort==activity&
1785             :filters=status,topic&
1786             :columns=title,status,fixer
1788 The index view is determined by two parts of the specifier: the layout
1789 part and the filter part. The layout part consists of the query
1790 parameters that begin with colons, and it determines the way that the
1791 properties of selected items are displayed. The filter part consists of
1792 all the other query parameters, and it determines the criteria by which
1793 items are selected for display. The filter part is interactively
1794 manipulated with the form widgets displayed in the filter section. The
1795 layout part is interactively manipulated by clicking on the column
1796 headings in the table.
1798 The filter part selects the union of the sets of items with values
1799 matching any specified Link properties and the intersection of the sets
1800 of items with values matching any specified Multilink properties.
1802 The example specifies an index of "issue" items. Only items with a
1803 "status" of either "unread" or "in-progress" or "resolved" are
1804 displayed, and only items with "topic" values including both "security"
1805 and "ui" are displayed. The items are grouped by priority, arranged in
1806 ascending order; and within groups, sorted by activity, arranged in
1807 descending order. The filter section shows filters for the "status" and
1808 "topic" properties, and the table includes columns for the "title",
1809 "status", and "fixer" properties.
1811 Searching Views
1812 ---------------
1814 Note: if you add a new column to the ``:columns`` form variable
1815       potentials then you will need to add the column to the appropriate
1816       `index views`_ template so that it is actually displayed.
1818 This is one of the class context views. The template used is typically
1819 "*classname*.search". The form on this page should have "search" as its
1820 ``@action`` variable. The "search" action:
1822 - sets up additional filtering, as well as performing indexed text
1823   searching
1824 - sets the ``:filter`` variable correctly
1825 - saves the query off if ``:query_name`` is set.
1827 The search page should lay out any fields that you wish to allow the
1828 user to search on. If your schema contains a large number of properties,
1829 you should be wary of making all of those properties available for
1830 searching, as this can cause confusion. If the additional properties are
1831 Strings, consider having their value indexed, and then they will be
1832 searchable using the full text indexed search. This is both faster, and
1833 more useful for the end user.
1835 The two special form values on search pages which are handled by the
1836 "search" action are:
1838 :search_text
1839   Text with which to perform a search of the text index. Results from
1840   that search will be used to limit the results of other filters (using
1841   an intersection operation)
1842 :query_name
1843   If supplied, the search parameters (including :search_text) will be
1844   saved off as a the query item and registered against the user's
1845   queries property. Note that the *classic* template schema has this
1846   ability, but the *minimal* template schema does not.
1849 Item Views
1850 ----------
1852 The basic view of a hyperdb item is provided by the "*classname*.item"
1853 template. It generally has three sections; an "editor", a "spool" and a
1854 "history" section.
1857 Editor Section
1858 ~~~~~~~~~~~~~~
1860 The editor section is used to manipulate the item - it may be a static
1861 display if the user doesn't have permission to edit the item.
1863 Here's an example of a basic editor template (this is the default
1864 "classic" template issue item edit form - from the "issue.item.html"
1865 template)::
1867  <table class="form">
1868  <tr>
1869   <th nowrap>Title</th>
1870   <td colspan="3" tal:content="structure python:context.title.field(size=60)">title</td>
1871  </tr>
1872  
1873  <tr>
1874   <th nowrap>Priority</th>
1875   <td tal:content="structure context/priority/menu">priority</td>
1876   <th nowrap>Status</th>
1877   <td tal:content="structure context/status/menu">status</td>
1878  </tr>
1879  
1880  <tr>
1881   <th nowrap>Superseder</th>
1882   <td>
1883    <span tal:replace="structure python:context.superseder.field(showid=1, size=20)" />
1884    <span tal:replace="structure python:db.issue.classhelp('id,title')" />
1885    <span tal:condition="context/superseder">
1886     <br>View: <span tal:replace="structure python:context.superseder.link(showid=1)" />
1887    </span>
1888   </td>
1889   <th nowrap>Nosy List</th>
1890   <td>
1891    <span tal:replace="structure context/nosy/field" />
1892    <span tal:replace="structure python:db.user.classhelp('username,realname,address,phone')" />
1893   </td>
1894  </tr>
1895  
1896  <tr>
1897   <th nowrap>Assigned To</th>
1898   <td tal:content="structure context/assignedto/menu">
1899    assignedto menu
1900   </td>
1901   <td>&nbsp;</td>
1902   <td>&nbsp;</td>
1903  </tr>
1904  
1905  <tr>
1906   <th nowrap>Change Note</th>
1907   <td colspan="3">
1908    <textarea name=":note" wrap="hard" rows="5" cols="60"></textarea>
1909   </td>
1910  </tr>
1911  
1912  <tr>
1913   <th nowrap>File</th>
1914   <td colspan="3"><input type="file" name=":file" size="40"></td>
1915  </tr>
1916  
1917  <tr>
1918   <td>&nbsp;</td>
1919   <td colspan="3" tal:content="structure context/submit">
1920    submit button will go here
1921   </td>
1922  </tr>
1923  </table>
1926 When a change is submitted, the system automatically generates a message
1927 describing the changed properties. As shown in the example, the editor
1928 template can use the ":note" and ":file" fields, which are added to the
1929 standard changenote message generated by Roundup.
1932 Form values
1933 :::::::::::
1935 We have a number of ways to pull properties out of the form in order to
1936 meet the various needs of:
1938 1. editing the current item (perhaps an issue item)
1939 2. editing information related to the current item (eg. messages or
1940    attached files)
1941 3. creating new information to be linked to the current item (eg. time
1942    spent on an issue)
1944 In the following, ``<bracketed>`` values are variable, ":" may be one of
1945 ":" or "@", and other text ("required") is fixed.
1947 Properties are specified as form variables:
1949 ``<propname>``
1950   property on the current context item
1952 ``<designator>:<propname>``
1953   property on the indicated item (for editing related information)
1955 ``<classname>-<N>:<propname>``
1956   property on the Nth new item of classname (generally for creating new
1957   items to attach to the current item)
1959 Once we have determined the "propname", we check to see if it is one of
1960 the special form values:
1962 ``@required``
1963   The named property values must be supplied or a ValueError will be
1964   raised.
1966 ``@remove@<propname>=id(s)``
1967   The ids will be removed from the multilink property.
1969 ``:add:<propname>=id(s)``
1970   The ids will be added to the multilink property.
1972 ``:link:<propname>=<designator>``
1973   Used to add a link to new items created during edit. These are
1974   collected and returned in ``all_links``. This will result in an
1975   additional linking operation (either Link set or Multilink append)
1976   after the edit/create is done using ``all_props`` in ``_editnodes``.
1977   The <propname> on the current item will be set/appended the id of the
1978   newly created item of class <designator> (where <designator> must be
1979   <classname>-<N>).
1981 Any of the form variables may be prefixed with a classname or
1982 designator.
1984 Two special form values are supported for backwards compatibility:
1986 ``:note``
1987   create a message (with content, author and date), linked to the
1988   context item. This is ALWAYS designated "msg-1".
1989 ``:file``
1990   create a file, attached to the current item and any message created by
1991   :note. This is ALWAYS designated "file-1".
1994 Spool Section
1995 ~~~~~~~~~~~~~
1997 The spool section lists related information like the messages and files
1998 of an issue.
2000 TODO
2003 History Section
2004 ~~~~~~~~~~~~~~~
2006 The final section displayed is the history of the item - its database
2007 journal. This is generally generated with the template::
2009  <tal:block tal:replace="structure context/history" />
2011 *To be done:*
2013 *The actual history entries of the item may be accessed for manual
2014 templating through the "journal" method of the item*::
2016  <tal:block tal:repeat="entry context/journal">
2017   a journal entry
2018  </tal:block>
2020 *where each journal entry is an HTMLJournalEntry.*
2022 Defining new web actions
2023 ------------------------
2025 You may define new actions to be triggered by the ``@action`` form
2026 variable. These are added to the tracker ``interfaces.py`` as methods on
2027 the ``Client`` class. 
2029 Adding action methods takes three steps; first you `define the new
2030 action method`_, then you `register the action method`_ with the cgi
2031 interface so it may be triggered by the ``@action`` form variable.
2032 Finally you `use the new action`_ in your HTML form.
2034 See "`setting up a "wizard" (or "druid") for controlled adding of
2035 issues`_" for an example.
2038 Define the new action method
2039 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2041 The action methods have the following interface::
2043     def myActionMethod(self):
2044         ''' Perform some action. No return value is required.
2045         '''
2047 The *self* argument is an instance of your tracker ``instance.Client``
2048 class - thus it's mostly implemented by ``roundup.cgi.Client``. See the
2049 docstring of that class for details of what it can do.
2051 The method will typically check the ``self.form`` variable's contents.
2052 It may then:
2054 - add information to ``self.ok_message`` or ``self.error_message``
2055 - change the ``self.template`` variable to alter what the user will see
2056   next
2057 - raise Unauthorised, SendStaticFile, SendFile, NotFound or Redirect
2058   exceptions
2061 Register the action method
2062 ~~~~~~~~~~~~~~~~~~~~~~~~~~
2064 The method is now written, but isn't available to the user until you add
2065 it to the `instance.Client`` class ``actions`` variable, like so::
2067     actions = client.Class.actions + (
2068         ('myaction', 'myActionMethod'),
2069     )
2071 This maps the action name "myaction" to the action method we defined.
2074 Use the new action
2075 ~~~~~~~~~~~~~~~~~~
2077 In your HTML form, add a hidden form element like so::
2079   <input type="hidden" name="@action" value="myaction">
2081 where "myaction" is the name you registered in the previous step.
2084 Examples
2085 ========
2087 .. contents::
2088    :local:
2089    :depth: 1
2092 Adding a new field to the classic schema
2093 ----------------------------------------
2095 This example shows how to add a new constrained property (i.e. a
2096 selection of distinct values) to your tracker.
2099 Introduction
2100 ~~~~~~~~~~~~
2102 To make the classic schema of roundup useful as a TODO tracking system
2103 for a group of systems administrators, it needed an extra data field per
2104 issue: a category.
2106 This would let sysadmins quickly list all TODOs in their particular area
2107 of interest without having to do complex queries, and without relying on
2108 the spelling capabilities of other sysadmins (a losing proposition at
2109 best).
2112 Adding a field to the database
2113 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2115 This is the easiest part of the change. The category would just be a
2116 plain string, nothing fancy. To change what is in the database you need
2117 to add some lines to the ``open()`` function in ``dbinit.py``. Under the
2118 comment::
2120     # add any additional database schema configuration here
2122 add::
2124     category = Class(db, "category", name=String())
2125     category.setkey("name")
2127 Here we are setting up a chunk of the database which we are calling
2128 "category". It contains a string, which we are refering to as "name" for
2129 lack of a more imaginative title. (Since "name" is one of the properties
2130 that Roundup looks for on items if you do not set a key for them, it's
2131 probably a good idea to stick with it for new classes if at all
2132 appropriate.) Then we are setting the key of this chunk of the database
2133 to be that "name". This is equivalent to an index for database types.
2134 This also means that there can only be one category with a given name.
2136 Adding the above lines allows us to create categories, but they're not
2137 tied to the issues that we are going to be creating. It's just a list of
2138 categories off on its own, which isn't much use. We need to link it in
2139 with the issues. To do that, find the lines in the ``open()`` function
2140 in ``dbinit.py`` which set up the "issue" class, and then add a link to
2141 the category::
2143     issue = IssueClass(db, "issue", ... ,
2144         category=Multilink("category"), ... )
2146 The ``Multilink()`` means that each issue can have many categories. If
2147 you were adding something with a one-to-one relationship to issues (such
2148 as the "assignedto" property), use ``Link()`` instead.
2150 That is all you need to do to change the schema. The rest of the effort
2151 is fiddling around so you can actually use the new category.
2154 Populating the new category class
2155 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2157 If you haven't initialised the database with the roundup-admin
2158 "initialise" command, then you can add the following to the tracker
2159 ``dbinit.py`` in the ``init()`` function under the comment::
2161     # add any additional database create steps here - but only if you
2162     # haven't initialised the database with the admin "initialise" command
2164 Add::
2166      category = db.getclass('category')
2167      category.create(name="scipy", order="1")
2168      category.create(name="chaco", order="2")
2169      category.create(name="weave", order="3")
2171 If the database has already been initalised, then you need to use the
2172 ``roundup-admin`` tool::
2174      % roundup-admin -i <tracker home>
2175      Roundup <version> ready for input.
2176      Type "help" for help.
2177      roundup> create category name=scipy order=1
2178      1
2179      roundup> create category name=chaco order=1
2180      2
2181      roundup> create category name=weave order=1
2182      3
2183      roundup> exit...
2184      There are unsaved changes. Commit them (y/N)? y
2186 TODO: explain why order=1 in each case. Also, does key get set to "name"
2187 automatically when added via roundup-admin?
2190 Setting up security on the new objects
2191 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2193 By default only the admin user can look at and change objects. This
2194 doesn't suit us, as we want any user to be able to create new categories
2195 as required, and obviously everyone needs to be able to view the
2196 categories of issues for it to be useful.
2198 We therefore need to change the security of the category objects. This
2199 is also done in the ``open()`` function of ``dbinit.py``.
2201 There are currently two loops which set up permissions and then assign
2202 them to various roles. Simply add the new "category" to both lists::
2204     # new permissions for this schema
2205     for cl in 'issue', 'file', 'msg', 'user', 'category':
2206         db.security.addPermission(name="Edit", klass=cl,
2207             description="User is allowed to edit "+cl)
2208         db.security.addPermission(name="View", klass=cl,
2209             description="User is allowed to access "+cl)
2211     # Assign the access and edit permissions for issue, file and message
2212     # to regular users now
2213     for cl in 'issue', 'file', 'msg', 'category':
2214         p = db.security.getPermission('View', cl)
2215         db.security.addPermissionToRole('User', p)
2216         p = db.security.getPermission('Edit', cl)
2217         db.security.addPermissionToRole('User', p)
2219 So you are in effect doing the following (with 'cl' substituted by its
2220 value)::
2222     db.security.addPermission(name="Edit", klass='category',
2223         description="User is allowed to edit "+'category')
2224     db.security.addPermission(name="View", klass='category',
2225         description="User is allowed to access "+'category')
2227 which is creating two permission types; that of editing and viewing
2228 "category" objects respectively. Then the following lines assign those
2229 new permissions to the "User" role, so that normal users can view and
2230 edit "category" objects::
2232     p = db.security.getPermission('View', 'category')
2233     db.security.addPermissionToRole('User', p)
2235     p = db.security.getPermission('Edit', 'category')
2236     db.security.addPermissionToRole('User', p)
2238 This is all the work that needs to be done for the database. It will
2239 store categories, and let users view and edit them. Now on to the
2240 interface stuff.
2243 Changing the web left hand frame
2244 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2246 We need to give the users the ability to create new categories, and the
2247 place to put the link to this functionality is in the left hand function
2248 bar, under the "Issues" area. The file that defines how this area looks
2249 is ``html/page``, which is what we are going to be editing next.
2251 If you look at this file you can see that it contains a lot of
2252 "classblock" sections which are chunks of HTML that will be included or
2253 excluded in the output depending on whether the condition in the
2254 classblock is met. Under the end of the classblock for issue is where we
2255 are going to add the category code::
2257   <p class="classblock"
2258      tal:condition="python:request.user.hasPermission('View', 'category')">
2259    <b>Categories</b><br>
2260    <a tal:condition="python:request.user.hasPermission('Edit', 'category')"
2261       href="category?@template=item">New Category<br></a>
2262   </p>
2264 The first two lines is the classblock definition, which sets up a
2265 condition that only users who have "View" permission for the "category"
2266 object will have this section included in their output. Next comes a
2267 plain "Categories" header in bold. Everyone who can view categories will
2268 get that.
2270 Next comes the link to the editing area of categories. This link will
2271 only appear if the condition - that the user has "Edit" permissions for
2272 the "category" objects - is matched. If they do have permission then
2273 they will get a link to another page which will let the user add new
2274 categories.
2276 Note that if you have permission to *view* but not to *edit* categories,
2277 then all you will see is a "Categories" header with nothing underneath
2278 it. This is obviously not very good interface design, but will do for
2279 now. I just claim that it is so I can add more links in this section
2280 later on. However to fix the problem you could change the condition in
2281 the classblock statement, so that only users with "Edit" permission
2282 would see the "Categories" stuff.
2285 Setting up a page to edit categories
2286 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2288 We defined code in the previous section which let users with the
2289 appropriate permissions see a link to a page which would let them edit
2290 conditions. Now we have to write that page.
2292 The link was for the *item* template of the *category* object. This
2293 translates into Roundup looking for a file called ``category.item.html``
2294 in the ``html`` tracker directory. This is the file that we are going to
2295 write now.
2297 First we add an info tag in a comment which doesn't affect the outcome
2298 of the code at all, but is useful for debugging. If you load a page in a
2299 browser and look at the page source, you can see which sections come
2300 from which files by looking for these comments::
2302     <!-- category.item -->
2304 Next we need to add in the METAL macro stuff so we get the normal page
2305 trappings::
2307  <tal:block metal:use-macro="templates/page/macros/icing">
2308   <title metal:fill-slot="head_title">Category editing</title>
2309   <td class="page-header-top" metal:fill-slot="body_title">
2310    <h2>Category editing</h2>
2311   </td>
2312   <td class="content" metal:fill-slot="content">
2314 Next we need to setup up a standard HTML form, which is the whole
2315 purpose of this file. We link to some handy javascript which sends the
2316 form through only once. This is to stop users hitting the send button
2317 multiple times when they are impatient and thus having the form sent
2318 multiple times::
2320     <form method="POST" onSubmit="return submit_once()"
2321           enctype="multipart/form-data">
2323 Next we define some code which sets up the minimum list of fields that
2324 we require the user to enter. There will be only one field - "name" - so
2325 they better put something in it, otherwise the whole form is pointless::
2327     <input type="hidden" name="@required" value="name">
2329 To get everything to line up properly we will put everything in a table,
2330 and put a nice big header on it so the user has an idea what is
2331 happening::
2333     <table class="form">
2334      <tr><th class="header" colspan="2">Category</th></tr>
2336 Next, we need the field into which the user is going to enter the new
2337 category. The "context.name.field(size=60)" bit tells Roundup to
2338 generate a normal HTML field of size 60, and the contents of that field
2339 will be the "name" variable of the current context (which is
2340 "category"). The upshot of this is that when the user types something in
2341 to the form, a new category will be created with that name::
2343     <tr>
2344      <th nowrap>Name</th>
2345      <td tal:content="structure python:context.name.field(size=60)">
2346      name</td>
2347     </tr>
2349 Then a submit button so that the user can submit the new category::
2351     <tr>
2352      <td>&nbsp;</td>
2353      <td colspan="3" tal:content="structure context/submit">
2354       submit button will go here
2355      </td>
2356     </tr>
2358 Finally we finish off the tags we used at the start to do the METAL
2359 stuff::
2361   </td>
2362  </tal:block>
2364 So putting it all together, and closing the table and form we get::
2366  <!-- category.item -->
2367  <tal:block metal:use-macro="templates/page/macros/icing">
2368   <title metal:fill-slot="head_title">Category editing</title>
2369   <td class="page-header-top" metal:fill-slot="body_title">
2370    <h2>Category editing</h2>
2371   </td>
2372   <td class="content" metal:fill-slot="content">
2373    <form method="POST" onSubmit="return submit_once()"
2374          enctype="multipart/form-data">
2376     <input type="hidden" name="@required" value="name">
2378     <table class="form">
2379      <tr><th class="header" colspan="2">Category</th></tr>
2381      <tr>
2382       <th nowrap>Name</th>
2383       <td tal:content="structure python:context.name.field(size=60)">
2384       name</td>
2385      </tr>
2387      <tr>
2388       <td>&nbsp;</td>
2389       <td colspan="3" tal:content="structure context/submit">
2390        submit button will go here
2391       </td>
2392      </tr>
2393     </table>
2394    </form>
2395   </td>
2396  </tal:block>
2398 This is quite a lot to just ask the user one simple question, but there
2399 is a lot of setup for basically one line (the form line) to do its work.
2400 To add another field to "category" would involve one more line (well,
2401 maybe a few extra to get the formatting correct).
2404 Adding the category to the issue
2405 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2407 We now have the ability to create issues to our heart's content, but
2408 that is pointless unless we can assign categories to issues.  Just like
2409 the ``html/category.item.html`` file was used to define how to add a new
2410 category, the ``html/issue.item.html`` is used to define how a new issue
2411 is created.
2413 Just like ``category.issue.html`` this file defines a form which has a
2414 table to lay things out. It doesn't matter where in the table we add new
2415 stuff, it is entirely up to your sense of aesthetics::
2417    <th nowrap>Category</th>
2418    <td><span tal:replace="structure context/category/field" />
2419        <span tal:replace="structure db/category/classhelp" />
2420    </td>
2422 First, we define a nice header so that the user knows what the next
2423 section is, then the middle line does what we are most interested in.
2424 This ``context/category/field`` gets replaced by a field which contains
2425 the category in the current context (the current context being the new
2426 issue).
2428 The classhelp lines generate a link (labelled "list") to a popup window
2429 which contains the list of currently known categories.
2432 Searching on categories
2433 ~~~~~~~~~~~~~~~~~~~~~~~
2435 We can add categories, and create issues with categories. The next
2436 obvious thing that we would like to be able to do, would be to search
2437 for issues based on their category, so that, for example, anyone working
2438 on the web server could look at all issues in the category "Web".
2440 If you look for "Search Issues" in the 'html/page.html' file, you will
2441 find that it looks something like 
2442 ``<a href="issue?@template=search">Search Issues</a>``. This shows us
2443 that when you click on "Search Issues" it will be looking for a
2444 ``issue.search.html`` file to display. So that is the file that we will
2445 change.
2447 If you look at this file it should be starting to seem familiar, although it
2448 does use some new macros. You can add the new category search code anywhere you
2449 like within that form::
2451   <tr tal:define="name string:category;
2452                   db_klass string:category;
2453                   db_content string:name;">
2454     <th>Priority:</th>
2455     <td metal:use-macro="search_select"></td>
2456     <td metal:use-macro="column_input"></td>
2457     <td metal:use-macro="sort_input"></td>
2458     <td metal:use-macro="group_input"></td>
2459   </tr>
2461 The definitions in the <tr> opening tag are used by the macros:
2463 - search_select expands to a drop-down box with all categories using db_klass
2464   and db_content.
2465 - column_input expands to a checkbox for selecting what columns should be
2466   displayed.
2467 - sort_input expands to a radio button for selecting what property should be
2468   sorted on.
2469 - group_input expands to a radio button for selecting what property should be
2470   group on.
2472 The category search code above would expand to the following::
2474   <tr>
2475     <th>Category:</th>
2476     <td>
2477       <select name="category">
2478         <option value="">don't care</option>
2479         <option value="">------------</option>      
2480         <option value="1">scipy</option>
2481         <option value="2">chaco</option>
2482         <option value="3">weave</option>
2483       </select>
2484     </td>
2485     <td><input type="checkbox" name=":columns" value="category"></td>
2486     <td><input type="radio" name=":sort" value="category"></td>
2487     <td><input type="radio" name=":group" value="category"></td>
2488   </tr>
2490 Adding category to the default view
2491 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2493 We can now add categories, add issues with categories, and search for
2494 issues based on categories. This is everything that we need to do;
2495 however, there is some more icing that we would like. I think the
2496 category of an issue is important enough that it should be displayed by
2497 default when listing all the issues.
2499 Unfortunately, this is a bit less obvious than the previous steps. The
2500 code defining how the issues look is in ``html/issue.index.html``. This
2501 is a large table with a form down at the bottom for redisplaying and so
2502 forth. 
2504 Firstly we need to add an appropriate header to the start of the table::
2506     <th tal:condition="request/show/category">Category</th>
2508 The *condition* part of this statement is to avoid displaying the
2509 Category column if the user has selected not to see it.
2511 The rest of the table is a loop which will go through every issue that
2512 matches the display criteria. The loop variable is "i" - which means
2513 that every issue gets assigned to "i" in turn.
2515 The new part of code to display the category will look like this::
2517     <td tal:condition="request/show/category"
2518         tal:content="i/category"></td>
2520 The condition is the same as above: only display the condition when the
2521 user hasn't asked for it to be hidden. The next part is to set the
2522 content of the cell to be the category part of "i" - the current issue.
2524 Finally we have to edit ``html/page.html`` again. This time, we need to
2525 tell it that when the user clicks on "Unasigned Issues" or "All Issues",
2526 the category column should be included in the resulting list. If you
2527 scroll down the page file, you can see the links with lots of options.
2528 The option that we are interested in is the ``:columns=`` one which
2529 tells roundup which fields of the issue to display. Simply add
2530 "category" to that list and it all should work.
2533 Adding in state transition control
2534 ----------------------------------
2536 Sometimes tracker admins want to control the states that users may move
2537 issues to. You can do this by following these steps:
2539 1. make "status" a required variable. This is achieved by adding the
2540    following to the top of the form in the ``issue.item.html``
2541    template::
2543      <input type="hidden" name="@required" value="status">
2545    this will force users to select a status.
2547 2. add a Multilink property to the status class::
2549      stat = Class(db, "status", ... , transitions=Multilink('status'),
2550                   ...)
2552    and then edit the statuses already created, either:
2554    a. through the web using the class list -> status class editor, or
2555    b. using the roundup-admin "set" command.
2557 3. add an auditor module ``checktransition.py`` in your tracker's
2558    ``detectors`` directory, for example::
2560      def checktransition(db, cl, nodeid, newvalues):
2561          ''' Check that the desired transition is valid for the "status"
2562              property.
2563          '''
2564          if not newvalues.has_key('status'):
2565              return
2566          current = cl.get(nodeid, 'status')
2567          new = newvalues['status']
2568          if new == current:
2569              return
2570          ok = db.status.get(current, 'transitions')
2571          if new not in ok:
2572              raise ValueError, 'Status not allowed to move from "%s" to "%s"'%(
2573                  db.status.get(current, 'name'), db.status.get(new, 'name'))
2575      def init(db):
2576          db.issue.audit('set', checktransition)
2578 4. in the ``issue.item.html`` template, change the status editing bit
2579    from::
2581     <th nowrap>Status</th>
2582     <td tal:content="structure context/status/menu">status</td>
2584    to::
2586     <th nowrap>Status</th>
2587     <td>
2588      <select tal:condition="context/id" name="status">
2589       <tal:block tal:define="ok context/status/transitions"
2590                  tal:repeat="state db/status/list">
2591        <option tal:condition="python:state.id in ok"
2592                tal:attributes="
2593                     value state/id;
2594                     selected python:state.id == context.status.id"
2595                tal:content="state/name"></option>
2596       </tal:block>
2597      </select>
2598      <tal:block tal:condition="not:context/id"
2599                 tal:replace="structure context/status/menu" />
2600     </td>
2602    which displays only the allowed status to transition to.
2605 Displaying only message summaries in the issue display
2606 ------------------------------------------------------
2608 Alter the issue.item template section for messages to::
2610  <table class="messages" tal:condition="context/messages">
2611   <tr><th colspan="5" class="header">Messages</th></tr>
2612   <tr tal:repeat="msg context/messages">
2613    <td><a tal:attributes="href string:msg${msg/id}"
2614           tal:content="string:msg${msg/id}"></a></td>
2615    <td tal:content="msg/author">author</td>
2616    <td nowrap tal:content="msg/date/pretty">date</td>
2617    <td tal:content="msg/summary">summary</td>
2618    <td>
2619     <a tal:attributes="href string:?@remove@messages=${msg/id}&@action=edit">
2620     remove</a>
2621    </td>
2622   </tr>
2623  </table>
2625 Restricting the list of users that are assignable to a task
2626 -----------------------------------------------------------
2628 1. In your tracker's "dbinit.py", create a new Role, say "Developer"::
2630      db.security.addRole(name='Developer', description='A developer')
2632 2. Just after that, create a new Permission, say "Fixer", specific to
2633    "issue"::
2635      p = db.security.addPermission(name='Fixer', klass='issue',
2636          description='User is allowed to be assigned to fix issues')
2638 3. Then assign the new Permission to your "Developer" Role::
2640      db.security.addPermissionToRole('Developer', p)
2642 4. In the issue item edit page ("html/issue.item.html" in your tracker
2643    directory), use the new Permission in restricting the "assignedto"
2644    list::
2646     <select name="assignedto">
2647      <option value="-1">- no selection -</option>
2648      <tal:block tal:repeat="user db/user/list">
2649      <option tal:condition="python:user.hasPermission(
2650                                 'Fixer', context._classname)"
2651              tal:attributes="
2652                 value user/id;
2653                 selected python:user.id == context.assignedto"
2654              tal:content="user/realname"></option>
2655      </tal:block>
2656     </select>
2658 For extra security, you may wish to setup an auditor to enforce the
2659 Permission requirement (install this as "assignedtoFixer.py" in your
2660 tracker "detectors" directory)::
2662   def assignedtoMustBeFixer(db, cl, nodeid, newvalues):
2663       ''' Ensure the assignedto value in newvalues is a used with the
2664           Fixer Permission
2665       '''
2666       if not newvalues.has_key('assignedto'):
2667           # don't care
2668           return
2669   
2670       # get the userid
2671       userid = newvalues['assignedto']
2672       if not db.security.hasPermission('Fixer', userid, cl.classname):
2673           raise ValueError, 'You do not have permission to edit %s'%cl.classname
2675   def init(db):
2676       db.issue.audit('set', assignedtoMustBeFixer)
2677       db.issue.audit('create', assignedtoMustBeFixer)
2679 So now, if an edit action attempts to set "assignedto" to a user that
2680 doesn't have the "Fixer" Permission, the error will be raised.
2683 Setting up a "wizard" (or "druid") for controlled adding of issues
2684 ------------------------------------------------------------------
2686 1. Set up the page templates you wish to use for data input. My wizard
2687    is going to be a two-step process: first figuring out what category
2688    of issue the user is submitting, and then getting details specific to
2689    that category. The first page includes a table of help, explaining
2690    what the category names mean, and then the core of the form::
2692     <form method="POST" onSubmit="return submit_once()"
2693           enctype="multipart/form-data">
2694       <input type="hidden" name="@template" value="add_page1">
2695       <input type="hidden" name="@action" value="page1submit">
2697       <strong>Category:</strong>
2698       <tal:block tal:replace="structure context/category/menu" />
2699       <input type="submit" value="Continue">
2700     </form>
2702    The next page has the usual issue entry information, with the
2703    addition of the following form fragments::
2705     <form method="POST" onSubmit="return submit_once()"
2706           enctype="multipart/form-data"
2707           tal:condition="context/is_edit_ok"
2708           tal:define="cat request/form/category/value">
2710       <input type="hidden" name="@template" value="add_page2">
2711       <input type="hidden" name="@required" value="title">
2712       <input type="hidden" name="category" tal:attributes="value cat">
2713        .
2714        .
2715        .
2716     </form>
2718    Note that later in the form, I test the value of "cat" include form
2719    elements that are appropriate. For example::
2721     <tal:block tal:condition="python:cat in '6 10 13 14 15 16 17'.split()">
2722      <tr>
2723       <th nowrap>Operating System</th>
2724       <td tal:content="structure context/os/field"></td>
2725      </tr>
2726      <tr>
2727       <th nowrap>Web Browser</th>
2728       <td tal:content="structure context/browser/field"></td>
2729      </tr>
2730     </tal:block>
2732    ... the above section will only be displayed if the category is one
2733    of 6, 10, 13, 14, 15, 16 or 17.
2735 3. Determine what actions need to be taken between the pages - these are
2736    usually to validate user choices and determine what page is next. Now
2737    encode those actions in methods on the ``interfaces.Client`` class
2738    and insert hooks to those actions in the "actions" attribute on that
2739    class, like so::
2741     actions = client.Client.actions + (
2742         ('page1_submit', 'page1SubmitAction'),
2743     )
2745     def page1SubmitAction(self):
2746         ''' Verify that the user has selected a category, and then move
2747             on to page 2.
2748         '''
2749         category = self.form['category'].value
2750         if category == '-1':
2751             self.error_message.append('You must select a category of report')
2752             return
2753         # everything's ok, move on to the next page
2754         self.template = 'add_page2'
2756 4. Use the usual "new" action as the ``@action`` on the final page, and
2757    you're done (the standard context/submit method can do this for you).
2760 Using an external password validation source
2761 --------------------------------------------
2763 We have a centrally-managed password changing system for our users. This
2764 results in a UN*X passwd-style file that we use for verification of
2765 users. Entries in the file consist of ``name:password`` where the
2766 password is encrypted using the standard UN*X ``crypt()`` function (see
2767 the ``crypt`` module in your Python distribution). An example entry
2768 would be::
2770     admin:aamrgyQfDFSHw
2772 Each user of Roundup must still have their information stored in the
2773 Roundup database - we just use the passwd file to check their password.
2774 To do this, we add the following code to our ``Client`` class in the
2775 tracker home ``interfaces.py`` module::
2777     def verifyPassword(self, userid, password):
2778         # get the user's username
2779         username = self.db.user.get(userid, 'username')
2781         # the passwords are stored in the "passwd.txt" file in the
2782         # tracker home
2783         file = os.path.join(self.db.config.TRACKER_HOME, 'passwd.txt')
2785         # see if we can find a match
2786         for ent in [line.strip().split(':') for line in
2787                                             open(file).readlines()]:
2788             if ent[0] == username:
2789                 return crypt.crypt(password, ent[1][:2]) == ent[1]
2791         # user doesn't exist in the file
2792         return 0
2794 What this does is look through the file, line by line, looking for a
2795 name that matches.
2797 We also remove the redundant password fields from the ``user.item``
2798 template.
2801 Adding a "vacation" flag to users for stopping nosy messages
2802 ------------------------------------------------------------
2804 When users go on vacation and set up vacation email bouncing, you'll
2805 start to see a lot of messages come back through Roundup "Fred is on
2806 vacation". Not very useful, and relatively easy to stop.
2808 1. add a "vacation" flag to your users::
2810          user = Class(db, "user",
2811                     username=String(),   password=Password(),
2812                     address=String(),    realname=String(),
2813                     phone=String(),      organisation=String(),
2814                     alternate_addresses=String(),
2815                     roles=String(), queries=Multilink("query"),
2816                     vacation=Boolean())
2818 2. So that users may edit the vacation flags, add something like the
2819    following to your ``user.item`` template::
2821      <tr>
2822       <th>On Vacation</th> 
2823       <td tal:content="structure context/vacation/field">vacation</td> 
2824      </tr> 
2826 3. edit your detector ``nosyreactor.py`` so that the ``nosyreaction()``
2827    consists of::
2829     def nosyreaction(db, cl, nodeid, oldvalues):
2830         # send a copy of all new messages to the nosy list
2831         for msgid in determineNewMessages(cl, nodeid, oldvalues):
2832             try:
2833                 users = db.user
2834                 messages = db.msg
2836                 # figure the recipient ids
2837                 sendto = []
2838                 r = {}
2839                 recipients = messages.get(msgid, 'recipients')
2840                 for recipid in messages.get(msgid, 'recipients'):
2841                     r[recipid] = 1
2843                 # figure the author's id, and indicate they've received
2844                 # the message
2845                 authid = messages.get(msgid, 'author')
2847                 # possibly send the message to the author, as long as
2848                 # they aren't anonymous
2849                 if (db.config.MESSAGES_TO_AUTHOR == 'yes' and
2850                         users.get(authid, 'username') != 'anonymous'):
2851                     sendto.append(authid)
2852                 r[authid] = 1
2854                 # now figure the nosy people who weren't recipients
2855                 nosy = cl.get(nodeid, 'nosy')
2856                 for nosyid in nosy:
2857                     # Don't send nosy mail to the anonymous user (that
2858                     # user shouldn't appear in the nosy list, but just
2859                     # in case they do...)
2860                     if users.get(nosyid, 'username') == 'anonymous':
2861                         continue
2862                     # make sure they haven't seen the message already
2863                     if not r.has_key(nosyid):
2864                         # send it to them
2865                         sendto.append(nosyid)
2866                         recipients.append(nosyid)
2868                 # generate a change note
2869                 if oldvalues:
2870                     note = cl.generateChangeNote(nodeid, oldvalues)
2871                 else:
2872                     note = cl.generateCreateNote(nodeid)
2874                 # we have new recipients
2875                 if sendto:
2876                     # filter out the people on vacation
2877                     sendto = [i for i in sendto 
2878                               if not users.get(i, 'vacation', 0)]
2880                     # map userids to addresses
2881                     sendto = [users.get(i, 'address') for i in sendto]
2883                     # update the message's recipients list
2884                     messages.set(msgid, recipients=recipients)
2886                     # send the message
2887                     cl.send_message(nodeid, msgid, note, sendto)
2888             except roundupdb.MessageSendError, message:
2889                 raise roundupdb.DetectorError, message
2891    Note that this is the standard nosy reaction code, with the small
2892    addition of::
2894     # filter out the people on vacation
2895     sendto = [i for i in sendto if not users.get(i, 'vacation', 0)]
2897    which filters out the users that have the vacation flag set to true.
2900 Adding a time log to your issues
2901 --------------------------------
2903 We want to log the dates and amount of time spent working on issues, and
2904 be able to give a summary of the total time spent on a particular issue.
2906 1. Add a new class to your tracker ``dbinit.py``::
2908     # storage for time logging
2909     timelog = Class(db, "timelog", period=Interval())
2911    Note that we automatically get the date of the time log entry
2912    creation through the standard property "creation".
2914 2. Link to the new class from your issue class (again, in
2915    ``dbinit.py``)::
2917     issue = IssueClass(db, "issue", 
2918                     assignedto=Link("user"), topic=Multilink("keyword"),
2919                     priority=Link("priority"), status=Link("status"),
2920                     times=Multilink("timelog"))
2922    the "times" property is the new link to the "timelog" class.
2924 3. We'll need to let people add in times to the issue, so in the web
2925    interface we'll have a new entry field. This is a special field
2926    because unlike the other fields in the issue.item template, it
2927    affects a different item (a timelog item) and not the template's
2928    item, an issue. We have a special syntax for form fields that affect
2929    items other than the template default item (see the cgi 
2930    documentation on `special form variables`_). In particular, we add a
2931    field to capture a new timelog item's perdiod::
2933     <tr> 
2934      <th nowrap>Time Log</th> 
2935      <td colspan=3><input type="text" name="timelog-1@period" /> 
2936       <br />(enter as '3y 1m 4d 2:40:02' or parts thereof) 
2937      </td> 
2938     </tr> 
2939          
2940    and another hidden field that links that new timelog item (new
2941    because it's marked as having id "-1") to the issue item. It looks
2942    like this::
2944      <input type="hidden" name="@link@times" value="timelog-1" />
2946    On submission, the "-1" timelog item will be created and assigned a
2947    real item id. The "times" property of the issue will have the new id
2948    added to it.
2950 4. We want to display a total of the time log times that have been
2951    accumulated for an issue. To do this, we'll need to actually write
2952    some Python code, since it's beyond the scope of PageTemplates to
2953    perform such calculations. We do this by adding a method to the
2954    TemplatingUtils class in our tracker ``interfaces.py`` module::
2956     class TemplatingUtils:
2957         ''' Methods implemented on this class will be available to HTML
2958             templates through the 'utils' variable.
2959         '''
2960         def totalTimeSpent(self, times):
2961             ''' Call me with a list of timelog items (which have an
2962                 Interval "period" property)
2963             '''
2964             total = Interval('')
2965             for time in times:
2966                 total += time.period._value
2967             return total
2969    Replace the ``pass`` line as we did in step 4 above with the Client
2970    class. As indicated in the docstrings, we will be able to access the
2971    ``totalTimeSpent`` method via the ``utils`` variable in our
2972    templates.
2974 5. Display the time log for an issue::
2976      <table class="otherinfo" tal:condition="context/times">
2977       <tr><th colspan="3" class="header">Time Log
2978        <tal:block
2979             tal:replace="python:utils.totalTimeSpent(context.times)" />
2980       </th></tr>
2981       <tr><th>Date</th><th>Period</th><th>Logged By</th></tr>
2982       <tr tal:repeat="time context/times">
2983        <td tal:content="time/creation"></td>
2984        <td tal:content="time/period"></td>
2985        <td tal:content="time/creator"></td>
2986       </tr>
2987      </table>
2989    I put this just above the Messages log in my issue display. Note our
2990    use of the ``totalTimeSpent`` method which will total up the times
2991    for the issue and return a new Interval. That will be automatically
2992    displayed in the template as text like "+ 1y 2:40" (1 year, 2 hours
2993    and 40 minutes).
2995 8. If you're using a persistent web server - roundup-server or
2996    mod_python for example - then you'll need to restart that to pick up
2997    the code changes. When that's done, you'll be able to use the new
2998    time logging interface.
3000 Using a UN*X passwd file as the user database
3001 ---------------------------------------------
3003 On some systems the primary store of users is the UN*X passwd file. It
3004 holds information on users such as their username, real name, password
3005 and primary user group.
3007 Roundup can use this store as its primary source of user information,
3008 but it needs additional information too - email address(es), roundup
3009 Roles, vacation flags, roundup hyperdb item ids, etc. Also, "retired"
3010 users must still exist in the user database, unlike some passwd files in
3011 which the users are removed when they no longer have access to a system.
3013 To make use of the passwd file, we therefore synchronise between the two
3014 user stores. We also use the passwd file to validate the user logins, as
3015 described in the previous example, `using an external password
3016 validation source`_. We keep the users lists in sync using a fairly
3017 simple script that runs once a day, or several times an hour if more
3018 immediate access is needed. In short, it:
3020 1. parses the passwd file, finding usernames, passwords and real names,
3021 2. compares that list to the current roundup user list:
3023    a. entries no longer in the passwd file are *retired*
3024    b. entries with mismatching real names are *updated*
3025    c. entries only exist in the passwd file are *created*
3027 3. send an email to administrators to let them know what's been done.
3029 The retiring and updating are simple operations, requiring only a call
3030 to ``retire()`` or ``set()``. The creation operation requires more
3031 information though - the user's email address and their roundup Roles.
3032 We're going to assume that the user's email address is the same as their
3033 login name, so we just append the domain name to that. The Roles are
3034 determined using the passwd group identifier - mapping their UN*X group
3035 to an appropriate set of Roles.
3037 The script to perform all this, broken up into its main components, is
3038 as follows. Firstly, we import the necessary modules and open the
3039 tracker we're to work on::
3041     import sys, os, smtplib
3042     from roundup import instance, date
3044     # open the tracker
3045     tracker_home = sys.argv[1]
3046     tracker = instance.open(tracker_home)
3048 Next we read in the *passwd* file from the tracker home::
3050     # read in the users
3051     file = os.path.join(tracker_home, 'users.passwd')
3052     users = [x.strip().split(':') for x in open(file).readlines()]
3054 Handle special users (those to ignore in the file, and those who don't
3055 appear in the file)::
3057     # users to not keep ever, pre-load with the users I know aren't
3058     # "real" users
3059     ignore = ['ekmmon', 'bfast', 'csrmail']
3061     # users to keep - pre-load with the roundup-specific users
3062     keep = ['comment_pool', 'network_pool', 'admin', 'dev-team',
3063             'cs_pool', 'anonymous', 'system_pool', 'automated']
3065 Now we map the UN*X group numbers to the Roles that users should have::
3067     roles = {
3068      '501': 'User,Tech',  # tech
3069      '502': 'User',       # finance
3070      '503': 'User,CSR',   # customer service reps
3071      '504': 'User',       # sales
3072      '505': 'User',       # marketing
3073     }
3075 Now we do all the work. Note that the body of the script (where we have
3076 the tracker database open) is wrapped in a ``try`` / ``finally`` clause,
3077 so that we always close the database cleanly when we're finished. So, we
3078 now do all the work::
3080     # open the database
3081     db = tracker.open('admin')
3082     try:
3083         # store away messages to send to the tracker admins
3084         msg = []
3086         # loop over the users list read in from the passwd file
3087         for user,passw,uid,gid,real,home,shell in users:
3088             if user in ignore:
3089                 # this user shouldn't appear in our tracker
3090                 continue
3091             keep.append(user)
3092             try:
3093                 # see if the user exists in the tracker
3094                 uid = db.user.lookup(user)
3096                 # yes, they do - now check the real name for correctness
3097                 if real != db.user.get(uid, 'realname'):
3098                     db.user.set(uid, realname=real)
3099                     msg.append('FIX %s - %s'%(user, real))
3100             except KeyError:
3101                 # nope, the user doesn't exist
3102                 db.user.create(username=user, realname=real,
3103                     address='%s@ekit-inc.com'%user, roles=roles[gid])
3104                 msg.append('ADD %s - %s (%s)'%(user, real, roles[gid]))
3106         # now check that all the users in the tracker are also in our
3107         # "keep" list - retire those who aren't
3108         for uid in db.user.list():
3109             user = db.user.get(uid, 'username')
3110             if user not in keep:
3111                 db.user.retire(uid)
3112                 msg.append('RET %s'%user)
3114         # if we did work, then send email to the tracker admins
3115         if msg:
3116             # create the email
3117             msg = '''Subject: %s user database maintenance
3119             %s
3120             '''%(db.config.TRACKER_NAME, '\n'.join(msg))
3122             # send the email
3123             smtp = smtplib.SMTP(db.config.MAILHOST)
3124             addr = db.config.ADMIN_EMAIL
3125             smtp.sendmail(addr, addr, msg)
3127         # now we're done - commit the changes
3128         db.commit()
3129     finally:
3130         # always close the database cleanly
3131         db.close()
3133 And that's it!
3136 Using an LDAP database for user information
3137 -------------------------------------------
3139 A script that reads users from an LDAP store using
3140 http://python-ldap.sf.net/ and then compares the list to the users in the
3141 roundup user database would be pretty easy to write. You'd then have it run
3142 once an hour / day (or on demand if you can work that into your LDAP store
3143 workflow). See the example `Using a UN*X passwd file as the user database`_
3144 for more information about doing this.
3146 To authenticate off the LDAP store (rather than using the passwords in the
3147 roundup user database) you'd use the same python-ldap module inside an
3148 extension to the cgi interface. You'd do this by adding a method called
3149 "verifyPassword" to the Client class in your tracker's interfaces.py
3150 module. The method is implemented by default as::
3152     def verifyPassword(self, userid, password):
3153         ''' Verify the password that the user has supplied
3154         '''
3155         stored = self.db.user.get(self.userid, 'password')
3156         if password == stored:
3157             return 1
3158         if not password and not stored:
3159             return 1
3160         return 0
3162 So you could reimplement this as something like::
3164     def verifyPassword(self, userid, password):
3165         ''' Verify the password that the user has supplied
3166         '''
3167         # look up some unique LDAP information about the user
3168         username = self.db.user.get(self.userid, 'username')
3169         # now verify the password supplied against the LDAP store
3172 Enabling display of either message summaries or the entire messages
3173 -------------------------------------------------------------------
3175 This is pretty simple - all we need to do is copy the code from the
3176 example `displaying only message summaries in the issue display`_ into
3177 our template alongside the summary display, and then introduce a switch
3178 that shows either one or the other. We'll use a new form variable,
3179 ``@whole_messages`` to achieve this::
3181  <table class="messages" tal:condition="context/messages">
3182   <tal:block tal:condition="not:request/form/@whole_messages/value | python:0">
3183    <tr><th colspan="3" class="header">Messages</th>
3184        <th colspan="2" class="header">
3185          <a href="?@whole_messages=yes">show entire messages</a>
3186        </th>
3187    </tr>
3188    <tr tal:repeat="msg context/messages">
3189     <td><a tal:attributes="href string:msg${msg/id}"
3190            tal:content="string:msg${msg/id}"></a></td>
3191     <td tal:content="msg/author">author</td>
3192     <td nowrap tal:content="msg/date/pretty">date</td>
3193     <td tal:content="msg/summary">summary</td>
3194     <td>
3195      <a tal:attributes="href string:?@remove@messages=${msg/id}&@action=edit">remove</a>
3196     </td>
3197    </tr>
3198   </tal:block>
3200   <tal:block tal:condition="request/form/@whole_messages/value | python:0">
3201    <tr><th colspan="2" class="header">Messages</th>
3202        <th class="header">
3203          <a href="?@whole_messages=">show only summaries</a>
3204        </th>
3205    </tr>
3206    <tal:block tal:repeat="msg context/messages">
3207     <tr>
3208      <th tal:content="msg/author">author</th>
3209      <th nowrap tal:content="msg/date/pretty">date</th>
3210      <th style="text-align: right">
3211       (<a tal:attributes="href string:?@remove@messages=${msg/id}&@action=edit">remove</a>)
3212      </th>
3213     </tr>
3214     <tr><td colspan="3" tal:content="msg/content"></td></tr>
3215    </tal:block>
3216   </tal:block>
3217  </table>
3220 Blocking issues that depend on other issues
3221 -------------------------------------------
3223 We needed the ability to mark certain issues as "blockers" - that is,
3224 they can't be resolved until another issue (the blocker) they rely on is
3225 resolved. To achieve this:
3227 1. Create a new property on the issue Class,
3228    ``blockers=Multilink("issue")``. Edit your tracker's dbinit.py file.
3229    Where the "issue" class is defined, something like::
3231     issue = IssueClass(db, "issue", 
3232                     assignedto=Link("user"), topic=Multilink("keyword"),
3233                     priority=Link("priority"), status=Link("status"))
3235    add the blockers entry like so::
3237     issue = IssueClass(db, "issue", 
3238                     blockers=Multilink("issue"),
3239                     assignedto=Link("user"), topic=Multilink("keyword"),
3240                     priority=Link("priority"), status=Link("status"))
3242 2. Add the new "blockers" property to the issue.item edit page, using
3243    something like::
3245     <th nowrap>Waiting On</th>
3246     <td>
3247      <span tal:replace="structure python:context.blockers.field(showid=1,
3248                                   size=20)" />
3249      <span tal:replace="structure python:db.issue.classhelp('id,title')" />
3250      <span tal:condition="context/blockers"
3251            tal:repeat="blk context/blockers">
3252       <br>View: <a tal:attributes="href string:issue${blk/id}"
3253                    tal:content="blk/id"></a>
3254      </span>
3256    You'll need to fiddle with your item page layout to find an
3257    appropriate place to put it - I'll leave that fun part up to you.
3258    Just make sure it appears in the first table, possibly somewhere near
3259    the "superseders" field.
3261 3. Create a new detector module (attached) which enforces the rules:
3263    - issues may not be resolved if they have blockers
3264    - when a blocker is resolved, it's removed from issues it blocks
3266    The contents of the detector should be something like this::
3268     def blockresolution(db, cl, nodeid, newvalues):
3269         ''' If the issue has blockers, don't allow it to be resolved.
3270         '''
3271         if nodeid is None:
3272             blockers = []
3273         else:
3274             blockers = cl.get(nodeid, 'blockers')
3275         blockers = newvalues.get('blockers', blockers)
3277         # don't do anything if there's no blockers or the status hasn't
3278         # changed
3279         if not blockers or not newvalues.has_key('status'):
3280             return
3282         # get the resolved state ID
3283         resolved_id = db.status.lookup('resolved')
3285         # format the info
3286         u = db.config.TRACKER_WEB
3287         s = ', '.join(['<a href="%sissue%s">%s</a>'%(
3288                         u,id,id) for id in blockers])
3289         if len(blockers) == 1:
3290             s = 'issue %s is'%s
3291         else:
3292             s = 'issues %s are'%s
3294         # ok, see if we're trying to resolve
3295         if newvalues['status'] == resolved_id:
3296             raise ValueError, "This issue can't be resolved until %s resolved."%s
3298     def resolveblockers(db, cl, nodeid, newvalues):
3299         ''' When we resolve an issue that's a blocker, remove it from the
3300             blockers list of the issue(s) it blocks.
3301         '''
3302         if not newvalues.has_key('status'):
3303             return
3305         # get the resolved state ID
3306         resolved_id = db.status.lookup('resolved')
3308         # interesting?
3309         if newvalues['status'] != resolved_id:
3310             return
3312         # yes - find all the blocked issues, if any, and remove me from
3313         # their blockers list
3314         issues = cl.find(blockers=nodeid)
3315         for issueid in issues:
3316             blockers = cl.get(issueid, 'blockers')
3317             if nodeid in blockers:
3318                 blockers.remove(nodeid)
3319                 cl.set(issueid, blockers=blockers)
3322     def init(db):
3323         # might, in an obscure situation, happen in a create
3324         db.issue.audit('create', blockresolution)
3325         db.issue.audit('set', blockresolution)
3327         # can only happen on a set
3328         db.issue.react('set', resolveblockers)
3330    Put the above code in a file called "blockers.py" in your tracker's
3331    "detectors" directory.
3333 4. Finally, and this is an optional step, modify the tracker web page
3334    URLs so they filter out issues with any blockers. You do this by
3335    adding an additional filter on "blockers" for the value "-1". For
3336    example, the existing "Show All" link in the "page" template (in the
3337    tracker's "html" directory) looks like this::
3339      <a href="issue?:sort=-activity&:group=priority&:filter=status&:columns=id,activity,title,creator,assignedto,status&status=-1,1,2,3,4,5,6,7">Show All</a><br>
3341    modify it to add the "blockers" info to the URL (note, both the
3342    ":filter" *and* "blockers" values must be specified)::
3344      <a href="issue?:sort=-activity&:group=priority&:filter=status,blockers&blockers=-1&:columns=id,activity,title,creator,assignedto,status&status=-1,1,2,3,4,5,6,7">Show All</a><br>
3346 That's it. You should now be able to set blockers on your issues. Note
3347 that if you want to know whether an issue has any other issues dependent
3348 on it (i.e. it's in their blockers list) you can look at the journal
3349 history at the bottom of the issue page - look for a "link" event to
3350 another issue's "blockers" property.
3353 -------------------
3355 Back to `Table of Contents`_
3357 .. _`Table of Contents`: index.html
3358 .. _`design documentation`: design.html