Code

various cosmetic fixes
[roundup.git] / doc / customizing.txt
1 ===================
2 Customising Roundup
3 ===================
5 :Version: $Revision: 1.94 $
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.
472 See the detectors section in the `design document`__ for details of the
473 interface for detectors.
475 __ design.html
477 Sample additional detectors that have been found useful will appear in
478 the ``'detectors'`` directory of the Roundup distribution. If you want
479 to use one, copy it to the ``'detectors'`` of your tracker instance:
481 **newissuecopy.py**
482   This detector sends an email to a team address whenever a new issue is
483   created. The address is hard-coded into the detector, so edit it
484   before you use it (look for the text 'team@team.host') or you'll get
485   email errors!
487   The detector code::
489     from roundup import roundupdb
491     def newissuecopy(db, cl, nodeid, oldvalues):
492         ''' Copy a message about new issues to a team address.
493         '''
494         # so use all the messages in the create
495         change_note = cl.generateCreateNote(nodeid)
497         # send a copy to the nosy list
498         for msgid in cl.get(nodeid, 'messages'):
499             try:
500                 # note: last arg must be a list
501                 cl.send_message(nodeid, msgid, change_note,
502                     ['team@team.host'])
503             except roundupdb.MessageSendError, message:
504                 raise roundupdb.DetectorError, message
506     def init(db):
507         db.issue.react('create', newissuecopy)
510 Database Content
511 ================
513 Note: if you modify the content of definitional classes, you'll most
514        likely need to edit the tracker `detectors`_ to reflect your
515        changes.
517 Customisation of the special "definitional" classes (eg. status,
518 priority, resolution, ...) may be done either before or after the
519 tracker is initialised. The actual method of doing so is completely
520 different in each case though, so be careful to use the right one.
522 **Changing content before tracker initialisation**
523     Edit the dbinit module in your tracker to alter the items created in
524     using the ``create()`` methods.
526 **Changing content after tracker initialisation**
527     As the "admin" user, click on the "class list" link in the web
528     interface to bring up a list of all database classes. Click on the
529     name of the class you wish to change the content of.
531     You may also use the ``roundup-admin`` interface's create, set and
532     retire methods to add, alter or remove items from the classes in
533     question.
535 See "`adding a new field to the classic schema`_" for an example that
536 requires database content changes.
539 Access Controls
540 ===============
542 A set of Permissions is built into the security module by default:
544 - Edit (everything)
545 - View (everything)
547 The default interfaces define:
549 - Web Registration
550 - Web Access
551 - Web Roles
552 - Email Registration
553 - Email Access
555 These are hooked into the default Roles:
557 - Admin (Edit everything, View everything, Web Roles)
558 - User (Web Access, Email Access)
559 - Anonymous (Web Registration, Email Registration)
561 And finally, the "admin" user gets the "Admin" Role, and the "anonymous"
562 user gets "Anonymous" assigned when the database is initialised on
563 installation. The two default schemas then define:
565 - Edit issue, View issue (both)
566 - Edit file, View file (both)
567 - Edit msg, View msg (both)
568 - Edit support, View support (extended only)
570 and assign those Permissions to the "User" Role. Put together, these
571 settings appear in the ``open()`` function of the tracker ``dbinit.py``
572 (the following is taken from the "minimal" template's ``dbinit.py``)::
574     #
575     # SECURITY SETTINGS
576     #
577     # new permissions for this schema
578     for cl in ('user', ):
579         db.security.addPermission(name="Edit", klass=cl,
580             description="User is allowed to edit "+cl)
581         db.security.addPermission(name="View", klass=cl,
582             description="User is allowed to access "+cl)
584     # and give the regular users access to the web and email interface
585     p = db.security.getPermission('Web Access')
586     db.security.addPermissionToRole('User', p)
587     p = db.security.getPermission('Email Access')
588     db.security.addPermissionToRole('User', p)
590     # May users view other user information? Comment these lines out
591     # if you don't want them to
592     p = db.security.getPermission('View', 'user')
593     db.security.addPermissionToRole('User', p)
595     # Assign the appropriate permissions to the anonymous user's
596     # Anonymous role. Choices here are:
597     # - Allow anonymous users to register through the web
598     p = db.security.getPermission('Web Registration')
599     db.security.addPermissionToRole('Anonymous', p)
600     # - Allow anonymous (new) users to register through the email
601     #   gateway
602     p = db.security.getPermission('Email Registration')
603     db.security.addPermissionToRole('Anonymous', p)
606 New User Roles
607 --------------
609 New users are assigned the Roles defined in the config file as:
611 - NEW_WEB_USER_ROLES
612 - NEW_EMAIL_USER_ROLES
615 Changing Access Controls
616 ------------------------
618 You may alter the configuration variables to change the Role that new
619 web or email users get, for example to not give them access to the web
620 interface if they register through email. 
622 You may use the ``roundup-admin`` "``security``" command to display the
623 current Role and Permission configuration in your tracker.
626 Adding a new Permission
627 ~~~~~~~~~~~~~~~~~~~~~~~
629 When adding a new Permission, you will need to:
631 1. add it to your tracker's dbinit so it is created
632 2. enable it for the Roles that should have it (verify with
633    "``roundup-admin security``")
634 3. add it to the relevant HTML interface templates
635 4. add it to the appropriate xxxPermission methods on in your tracker
636    interfaces module
639 Example Scenarios
640 ~~~~~~~~~~~~~~~~~
642 **automatic registration of users in the e-mail gateway**
643  By giving the "anonymous" user the "Email Registration" Role, any
644  unidentified user will automatically be registered with the tracker
645  (with no password, so they won't be able to log in through the web
646  until an admin sets their password). Note: this is the default
647  behaviour in the tracker templates that ship with Roundup.
649 **anonymous access through the e-mail gateway**
650  Give the "anonymous" user the "Email Access" and ("Edit", "issue")
651  Roles but do not not give them the "Email Registration" Role. This
652  means that when an unknown user sends email into the tracker, they're
653  automatically logged in as "anonymous". Since they don't have the
654  "Email Registration" Role, they won't be automatically registered, but
655  since "anonymous" has permission to use the gateway, they'll still be
656  able to submit issues. Note that the Sender information - their email
657  address - will not be available - they're *anonymous*.
659 **only developers may be assigned issues**
660  Create a new Permission called "Fixer" for the "issue" class. Create a
661  new Role "Developer" which has that Permission, and assign that to the
662  appropriate users. Filter the list of users available in the assignedto
663  list to include only those users. Enforce the Permission with an
664  auditor. See the example 
665  `restricting the list of users that are assignable to a task`_.
667 **only managers may sign off issues as complete**
668  Create a new Permission called "Closer" for the "issue" class. Create a
669  new Role "Manager" which has that Permission, and assign that to the
670  appropriate users. In your web interface, only display the "resolved"
671  issue state option when the user has the "Closer" Permissions. Enforce
672  the Permission with an auditor. This is very similar to the previous
673  example, except that the web interface check would look like::
675    <option tal:condition="python:request.user.hasPermission('Closer')"
676            value="resolved">Resolved</option>
677  
678 **don't give web access to users who register through email**
679  Create a new Role called "Email User" which has all the Permissions of
680  the normal "User" Role minus the "Web Access" Permission. This will
681  allow users to send in emails to the tracker, but not access the web
682  interface.
684 **let some users edit the details of all users**
685  Create a new Role called "User Admin" which has the Permission for
686  editing users::
688     db.security.addRole(name='User Admin', description='Managing users')
689     p = db.security.getPermission('Edit', 'user')
690     db.security.addPermissionToRole('User Admin', p)
692  and assign the Role to the users who need the permission.
695 Web Interface
696 =============
698 .. contents::
699    :local:
700    :depth: 1
702 The web interface is provided by the ``roundup.cgi.client`` module and
703 is used by ``roundup.cgi``, ``roundup-server`` and ``ZRoundup``
704 (``ZRoundup``  is broken, until further notice). In all cases, we
705 determine which tracker is being accessed (the first part of the URL
706 path inside the scope of the CGI handler) and pass control on to the
707 tracker ``interfaces.Client`` class - which uses the ``Client`` class
708 from ``roundup.cgi.client`` - which handles the rest of the access
709 through its ``main()`` method. This means that you can do pretty much
710 anything you want as a web interface to your tracker.
712 Repercussions of changing the tracker schema
713 ---------------------------------------------
715 If you choose to change the `tracker schema`_ you will need to ensure
716 the web interface knows about it:
718 1. Index, item and search pages for the relevant classes may need to
719    have properties added or removed,
720 2. The "page" template may require links to be changed, as might the
721    "home" page's content arguments.
723 How requests are processed
724 --------------------------
726 The basic processing of a web request proceeds as follows:
728 1. figure out who we are, defaulting to the "anonymous" user
729 2. figure out what the request is for - we call this the "context"
730 3. handle any requested action (item edit, search, ...)
731 4. render the template requested by the context, resulting in HTML
732    output
734 In some situations, exceptions occur:
736 - HTTP Redirect  (generally raised by an action)
737 - SendFile       (generally raised by ``determine_context``)
738     here we serve up a FileClass "content" property
739 - SendStaticFile (generally raised by ``determine_context``)
740     here we serve up a file from the tracker "html" directory
741 - Unauthorised   (generally raised by an action)
742     here the action is cancelled, the request is rendered and an error
743     message is displayed indicating that permission was not granted for
744     the action to take place
745 - NotFound       (raised wherever it needs to be)
746     this exception percolates up to the CGI interface that called the
747     client
749 Determining web context
750 -----------------------
752 To determine the "context" of a request, we look at the URL and the
753 special request variable ``@template``. The URL path after the tracker
754 identifier is examined. Typical URL paths look like:
756 1.  ``/tracker/issue``
757 2.  ``/tracker/issue1``
758 3.  ``/tracker/_file/style.css``
759 4.  ``/cgi-bin/roundup.cgi/tracker/file1``
760 5.  ``/cgi-bin/roundup.cgi/tracker/file1/kitten.png``
762 where the "tracker identifier" is "tracker" in the above cases. That means
763 we're looking at "issue", "issue1", "_file/style.css", "file1" and
764 "file1/kitten.png" in the cases above. The path is generally only one
765 entry long - longer paths are handled differently.
767 a. if there is no path, then we are in the "home" context.
768 b. if the path starts with "_file" (as in example 3,
769    "/tracker/_file/style.css"), then the additional path entry,
770    "style.css" specifies the filename of a static file we're to serve up
771    from the tracker "html" directory. Raises a SendStaticFile exception.
772 c. if there is something in the path (as in example 1, "issue"), it
773    identifies the tracker class we're to display.
774 d. if the path is an item designator (as in examples 2 and 4, "issue1"
775    and "file1"), then we're to display a specific item.
776 e. if the path starts with an item designator and is longer than one
777    entry (as in example 5, "file1/kitten.png"), then we're assumed to be
778    handling an item of a ``FileClass``, and the extra path information
779    gives the filename that the client is going to label the download
780    with (i.e. "file1/kitten.png" is nicer to download than "file1").
781    This raises a ``SendFile`` exception.
783 Both b. and e. stop before we bother to determine the template we're
784 going to use. That's because they don't actually use templates.
786 The template used is specified by the ``@template`` CGI variable, which
787 defaults to:
789 - only classname suplied:        "index"
790 - full item designator supplied: "item"
793 Performing actions in web requests
794 ----------------------------------
796 When a user requests a web page, they may optionally also request for an
797 action to take place. As described in `how requests are processed`_, the
798 action is performed before the requested page is generated. Actions are
799 triggered by using a ``@action`` CGI variable, where the value is one
800 of:
802 **login**
803  Attempt to log a user in.
805 **logout**
806  Log the user out - make them "anonymous".
808 **register**
809  Attempt to create a new user based on the contents of the form and then
810  log them in.
812 **edit**
813  Perform an edit of an item in the database. There are some `special form
814  variables`_ you may use.
816 **new**
817  Add a new item to the database. You may use the same `special form
818  variables`_ as in the "edit" action.
820 **retire**
821  Retire the item in the database.
823 **editCSV**
824  Performs an edit of all of a class' items in one go. See also the
825  *class*.csv templating method which generates the CSV data to be
826  edited, and the ``'_generic.index'`` template which uses both of these
827  features.
829 **search**
830  Mangle some of the form variables:
832  - Set the form ":filter" variable based on the values of the filter
833    variables - if they're set to anything other than "dontcare" then add
834    them to :filter.
836  - Also handle the ":queryname" variable and save off the query to the
837    user's query list.
839 Each of the actions is implemented by a corresponding ``*actionAction*``
840 (where "action" is the name of the action) method on the
841 ``roundup.cgi.Client`` class, which also happens to be available in your
842 tracker instance as ``interfaces.Client``. So if you need to define new
843 actions, you may add them there (see `defining new web actions`_).
845 Each action also has a corresponding ``*actionPermission*`` (where
846 "action" is the name of the action) method which determines whether the
847 action is permissible given the current user. The base permission checks
848 are:
850 **login**
851  Determine whether the user has permission to log in. Base behaviour is
852  to check the user has "Web Access".
853 **logout**
854  No permission checks are made.
855 **register**
856  Determine whether the user has permission to register. Base behaviour
857  is to check the user has the "Web Registration" Permission.
858 **edit**
859  Determine whether the user has permission to edit this item. Base
860  behaviour is to check whether the user can edit this class. If we're
861  editing the "user" class, users are allowed to edit their own details -
862  unless they try to edit the "roles" property, which requires the
863  special Permission "Web Roles".
864 **new**
865  Determine whether the user has permission to create (or edit) this
866  item. Base behaviour is to check the user can edit this class. No
867  additional property checks are made. Additionally, new user items may
868  be created if the user has the "Web Registration" Permission.
869 **editCSV**
870  Determine whether the user has permission to edit this class. Base
871  behaviour is to check whether the user may edit this class.
872 **search**
873  Determine whether the user has permission to search this class. Base
874  behaviour is to check whether the user may view this class.
877 Special form variables
878 ----------------------
880 Item properties and their values are edited with html FORM
881 variables and their values. You can:
883 - Change the value of some property of the current item.
884 - Create a new item of any class, and edit the new item's
885   properties,
886 - Attach newly created items to a multilink property of the
887   current item.
888 - Remove items from a multilink property of the current item.
889 - Specify that some properties are required for the edit
890   operation to be successful.
892 In the following, <bracketed> values are variable, "@" may be
893 either ":" or "@", and other text "required" is fixed.
895 Most properties are specified as form variables:
897 ``<propname>``
898   property on the current context item
900 ``<designator>"@"<propname>``
901   property on the indicated item (for editing related information)
903 Designators name a specific item of a class.
905 ``<classname><N>``
906     Name an existing item of class <classname>.
908 ``<classname>"-"<N>``
909     Name the <N>th new item of class <classname>. If the form
910     submission is successful, a new item of <classname> is
911     created. Within the submitted form, a particular
912     designator of this form always refers to the same new
913     item.
915 Once we have determined the "propname", we look at it to see
916 if it's special:
918 ``@required``
919     The associated form value is a comma-separated list of
920     property names that must be specified when the form is
921     submitted for the edit operation to succeed.  
923     When the <designator> is missing, the properties are
924     for the current context item.  When <designator> is
925     present, they are for the item specified by
926     <designator>.
928     The "@required" specifier must come before any of the
929     properties it refers to are assigned in the form.
931 ``@remove@<propname>=id(s)`` or ``@add@<propname>=id(s)``
932     The "@add@" and "@remove@" edit actions apply only to
933     Multilink properties.  The form value must be a
934     comma-separate list of keys for the class specified by
935     the simple form variable.  The listed items are added
936     to (respectively, removed from) the specified
937     property.
939 ``@link@<propname>=<designator>``
940     If the edit action is "@link@", the simple form
941     variable must specify a Link or Multilink property.
942     The form value is a comma-separated list of
943     designators.  The item corresponding to each
944     designator is linked to the property given by simple
945     form variable.
947 None of the above (ie. just a simple form value)
948     The value of the form variable is converted
949     appropriately, depending on the type of the property.
951     For a Link('klass') property, the form value is a
952     single key for 'klass', where the key field is
953     specified in dbinit.py.  
955     For a Multilink('klass') property, the form value is a
956     comma-separated list of keys for 'klass', where the
957     key field is specified in dbinit.py.  
959     Note that for simple-form-variables specifiying Link
960     and Multilink properties, the linked-to class must
961     have a key field.
963     For a String() property specifying a filename, the
964     file named by the form value is uploaded. This means we
965     try to set additional properties "filename" and "type" (if
966     they are valid for the class).  Otherwise, the property
967     is set to the form value.
969     For Date(), Interval(), Boolean(), and Number()
970     properties, the form value is converted to the
971     appropriate
973 Any of the form variables may be prefixed with a classname or
974 designator.
976 Two special form values are supported for backwards compatibility:
978 @note
979     This is equivalent to::
981         @link@messages=msg-1
982         @msg-1@content=value
984     except that in addition, the "author" and "date" properties of
985     "msg-1" are set to the userid of the submitter, and the current
986     time, respectively.
988 @file
989     This is equivalent to::
991         @link@files=file-1
992         @file-1@content=value
994     The String content value is handled as described above for file
995     uploads.
997 If both the "@note" and "@file" form variables are
998 specified, the action::
1000         @link@msg-1@files=file-1
1002 is also performed.
1004 We also check that FileClass items have a "content" property with
1005 actual content, otherwise we remove them from all_props before
1006 returning.
1010 Default templates
1011 -----------------
1013 Most customisation of the web view can be done by modifying the
1014 templates in the tracker ``'html'`` directory. There are several types
1015 of files in there. The *minimal* template includes:
1017 **page.html**
1018   This template usually defines the overall look of your tracker. When
1019   you view an issue, it appears inside this template. When you view an
1020   index, it also appears inside this template. This template defines a
1021   macro called "icing" which is used by almost all other templates as a
1022   coating for their content, using its "content" slot. It also defines
1023   the "head_title" and "body_title" slots to allow setting of the page
1024   title.
1025 **home.html**
1026   the default page displayed when no other page is indicated by the user
1027 **home.classlist.html**
1028   a special version of the default page that lists the classes in the
1029   tracker
1030 **classname.item.html**
1031   displays an item of the *classname* class
1032 **classname.index.html**
1033   displays a list of *classname* items
1034 **classname.search.html**
1035   displays a search page for *classname* items
1036 **_generic.index.html**
1037   used to display a list of items where there is no
1038   ``*classname*.index`` available
1039 **_generic.help.html**
1040   used to display a "class help" page where there is no
1041   ``*classname*.help``
1042 **user.register.html**
1043   a special page just for the user class, that renders the registration
1044   page
1045 **style.css.html**
1046   a static file that is served up as-is
1048 The *classic* template has a number of additional templates.
1050 Note: Remember that you can create any template extension you want to,
1051 so if you just want to play around with the templating for new issues,
1052 you can copy the current "issue.item" template to "issue.test", and then
1053 access the test template using the "@template" URL argument::
1055    http://your.tracker.example/tracker/issue?@template=test
1057 and it won't affect your users using the "issue.item" template.
1060 How the templates work
1061 ----------------------
1064 Basic Templating Actions
1065 ~~~~~~~~~~~~~~~~~~~~~~~~
1067 Roundup's templates consist of special attributes on the HTML tags.
1068 These attributes form the Template Attribute Language, or TAL. The basic
1069 TAL commands are:
1071 **tal:define="variable expression; variable expression; ..."**
1072    Define a new variable that is local to this tag and its contents. For
1073    example::
1075       <html tal:define="title request/description">
1076        <head><title tal:content="title"></title></head>
1077       </html>
1079    In this example, the variable "title" is defined as the result of the
1080    expression "request/description". The "tal:content" command inside the
1081    <html> tag may then use the "title" variable.
1083 **tal:condition="expression"**
1084    Only keep this tag and its contents if the expression is true. For
1085    example::
1087      <p tal:condition="python:request.user.hasPermission('View', 'issue')">
1088       Display some issue information.
1089      </p>
1091    In the example, the <p> tag and its contents are only displayed if
1092    the user has the "View" permission for issues. We consider the number
1093    zero, a blank string, an empty list, and the built-in variable
1094    nothing to be false values. Nearly every other value is true,
1095    including non-zero numbers, and strings with anything in them (even
1096    spaces!).
1098 **tal:repeat="variable expression"**
1099    Repeat this tag and its contents for each element of the sequence
1100    that the expression returns, defining a new local variable and a
1101    special "repeat" variable for each element. For example::
1103      <tr tal:repeat="u user/list">
1104       <td tal:content="u/id"></td>
1105       <td tal:content="u/username"></td>
1106       <td tal:content="u/realname"></td>
1107      </tr>
1109    The example would iterate over the sequence of users returned by
1110    "user/list" and define the local variable "u" for each entry.
1112 **tal:replace="expression"**
1113    Replace this tag with the result of the expression. For example::
1115     <span tal:replace="request/user/realname" />
1117    The example would replace the <span> tag and its contents with the
1118    user's realname. If the user's realname was "Bruce", then the
1119    resultant output would be "Bruce".
1121 **tal:content="expression"**
1122    Replace the contents of this tag with the result of the expression.
1123    For example::
1125     <span tal:content="request/user/realname">user's name appears here
1126     </span>
1128    The example would replace the contents of the <span> tag with the
1129    user's realname. If the user's realname was "Bruce" then the
1130    resultant output would be "<span>Bruce</span>".
1132 **tal:attributes="attribute expression; attribute expression; ..."**
1133    Set attributes on this tag to the results of expressions. For
1134    example::
1136      <a tal:attributes="href string:user${request/user/id}">My Details</a>
1138    In the example, the "href" attribute of the <a> tag is set to the
1139    value of the "string:user${request/user/id}" expression, which will
1140    be something like "user123".
1142 **tal:omit-tag="expression"**
1143    Remove this tag (but not its contents) if the expression is true. For
1144    example::
1146       <span tal:omit-tag="python:1">Hello, world!</span>
1148    would result in output of::
1150       Hello, world!
1152 Note that the commands on a given tag are evaulated in the order above,
1153 so *define* comes before *condition*, and so on.
1155 Additionally, you may include tags such as <tal:block>, which are
1156 removed from output. Its content is kept, but the tag itself is not (so
1157 don't go using any "tal:attributes" commands on it). This is useful for
1158 making arbitrary blocks of HTML conditional or repeatable (very handy
1159 for repeating multiple table rows, which would othewise require an
1160 illegal tag placement to effect the repeat).
1163 Templating Expressions
1164 ~~~~~~~~~~~~~~~~~~~~~~
1166 The expressions you may use in the attribute values may be one of the
1167 following forms:
1169 **Path Expressions** - eg. ``item/status/checklist``
1170    These are object attribute / item accesses. Roughly speaking, the
1171    path ``item/status/checklist`` is broken into parts ``item``,
1172    ``status`` and ``checklist``. The ``item`` part is the root of the
1173    expression. We then look for a ``status`` attribute on ``item``, or
1174    failing that, a ``status`` item (as in ``item['status']``). If that
1175    fails, the path expression fails. When we get to the end, the object
1176    we're left with is evaluated to get a string - if it is a method, it
1177    is called; if it is an object, it is stringified. Path expressions
1178    may have an optional ``path:`` prefix, but they are the default
1179    expression type, so it's not necessary.
1181    If an expression evaluates to ``default``, then the expression is
1182    "cancelled" - whatever HTML already exists in the template will
1183    remain (tag content in the case of ``tal:content``, attributes in the
1184    case of ``tal:attributes``).
1186    If an expression evaluates to ``nothing`` then the target of the
1187    expression is removed (tag content in the case of ``tal:content``,
1188    attributes in the case of ``tal:attributes`` and the tag itself in
1189    the case of ``tal:replace``).
1191    If an element in the path may not exist, then you can use the ``|``
1192    operator in the expression to provide an alternative. So, the
1193    expression ``request/form/foo/value | default`` would simply leave
1194    the current HTML in place if the "foo" form variable doesn't exist.
1196    You may use the python function ``path``, as in
1197    ``path("item/status")``, to embed path expressions in Python
1198    expressions.
1200 **String Expressions** - eg. ``string:hello ${user/name}`` 
1201    These expressions are simple string interpolations - though they can
1202    be just plain strings with no interpolation if you want. The
1203    expression in the ``${ ... }`` is just a path expression as above.
1205 **Python Expressions** - eg. ``python: 1+1`` 
1206    These expressions give the full power of Python. All the "root level"
1207    variables are available, so ``python:item.status.checklist()`` would
1208    be equivalent to ``item/status/checklist``, assuming that
1209    ``checklist`` is a method.
1211 Modifiers:
1213 **structure** - eg. ``structure python:msg.content.plain(hyperlink=1)``
1214    The result of expressions are normally *escaped* to be safe for HTML
1215    display (all "<", ">" and "&" are turned into special entities). The
1216    ``structure`` expression modifier turns off this escaping - the
1217    result of the expression is now assumed to be HTML, which is passed
1218    to the web browser for rendering.
1220 **not:** - eg. ``not:python:1=1``
1221    This simply inverts the logical true/false value of another
1222    expression.
1225 Template Macros
1226 ~~~~~~~~~~~~~~~
1228 Macros are used in Roundup to save us from repeating the same common
1229 page stuctures over and over. The most common (and probably only) macro
1230 you'll use is the "icing" macro defined in the "page" template.
1232 Macros are generated and used inside your templates using special
1233 attributes similar to the `basic templating actions`_. In this case,
1234 though, the attributes belong to the Macro Expansion Template Attribute
1235 Language, or METAL. The macro commands are:
1237 **metal:define-macro="macro name"**
1238   Define that the tag and its contents are now a macro that may be
1239   inserted into other templates using the *use-macro* command. For
1240   example::
1242     <html metal:define-macro="page">
1243      ...
1244     </html>
1246   defines a macro called "page" using the ``<html>`` tag and its
1247   contents. Once defined, macros are stored on the template they're
1248   defined on in the ``macros`` attribute. You can access them later on
1249   through the ``templates`` variable, eg. the most common
1250   ``templates/page/macros/icing`` to access the "page" macro of the
1251   "page" template.
1253 **metal:use-macro="path expression"**
1254   Use a macro, which is identified by the path expression (see above).
1255   This will replace the current tag with the identified macro contents.
1256   For example::
1258    <tal:block metal:use-macro="templates/page/macros/icing">
1259     ...
1260    </tal:block>
1262    will replace the tag and its contents with the "page" macro of the
1263    "page" template.
1265 **metal:define-slot="slot name"** and **metal:fill-slot="slot name"**
1266   To define *dynamic* parts of the macro, you define "slots" which may
1267   be filled when the macro is used with a *use-macro* command. For
1268   example, the ``templates/page/macros/icing`` macro defines a slot like
1269   so::
1271     <title metal:define-slot="head_title">title goes here</title>
1273   In your *use-macro* command, you may now use a *fill-slot* command
1274   like this::
1276     <title metal:fill-slot="head_title">My Title</title>
1278   where the tag that fills the slot completely replaces the one defined
1279   as the slot in the macro.
1281 Note that you may not mix METAL and TAL commands on the same tag, but
1282 TAL commands may be used freely inside METAL-using tags (so your
1283 *fill-slots* tags may have all manner of TAL inside them).
1286 Information available to templates
1287 ----------------------------------
1289 Note: this is implemented by
1290 ``roundup.cgi.templating.RoundupPageTemplate``
1292 The following variables are available to templates.
1294 **context**
1295   The current context. This is either None, a `hyperdb class wrapper`_
1296   or a `hyperdb item wrapper`_
1297 **request**
1298   Includes information about the current request, including:
1299    - the current index information (``filterspec``, ``filter`` args,
1300      ``properties``, etc) parsed out of the form. 
1301    - methods for easy filterspec link generation
1302    - *user*, the current user item as an HTMLItem instance
1303    - *form*
1304      The current CGI form information as a mapping of form argument name
1305      to value
1306 **config**
1307   This variable holds all the values defined in the tracker config.py
1308   file (eg. TRACKER_NAME, etc.)
1309 **db**
1310   The current database, used to access arbitrary database items.
1311 **templates**
1312   Access to all the tracker templates by name. Used mainly in
1313   *use-macro* commands.
1314 **utils**
1315   This variable makes available some utility functions like batching.
1316 **nothing**
1317   This is a special variable - if an expression evaluates to this, then
1318   the tag (in the case of a ``tal:replace``), its contents (in the case
1319   of ``tal:content``) or some attributes (in the case of
1320   ``tal:attributes``) will not appear in the the output. So, for
1321   example::
1323     <span tal:attributes="class nothing">Hello, World!</span>
1325   would result in::
1327     <span>Hello, World!</span>
1329 **default**
1330   Also a special variable - if an expression evaluates to this, then the
1331   existing HTML in the template will not be replaced or removed, it will
1332   remain. So::
1334     <span tal:replace="default">Hello, World!</span>
1336   would result in::
1338     <span>Hello, World!</span>
1341 The context variable
1342 ~~~~~~~~~~~~~~~~~~~~
1344 The *context* variable is one of three things based on the current
1345 context (see `determining web context`_ for how we figure this out):
1347 1. if we're looking at a "home" page, then it's None
1348 2. if we're looking at a specific hyperdb class, it's a
1349    `hyperdb class wrapper`_.
1350 3. if we're looking at a specific hyperdb item, it's a
1351    `hyperdb item wrapper`_.
1353 If the context is not None, we can access the properties of the class or
1354 item. The only real difference between cases 2 and 3 above are:
1356 1. the properties may have a real value behind them, and this will
1357    appear if the property is displayed through ``context/property`` or
1358    ``context/property/field``.
1359 2. the context's "id" property will be a false value in the second case,
1360    but a real, or true value in the third. Thus we can determine whether
1361    we're looking at a real item from the hyperdb by testing
1362    "context/id".
1364 Hyperdb class wrapper
1365 :::::::::::::::::::::
1367 Note: this is implemented by the ``roundup.cgi.templating.HTMLClass``
1368 class.
1370 This wrapper object provides access to a hyperb class. It is used
1371 primarily in both index view and new item views, but it's also usable
1372 anywhere else that you wish to access information about a class, or the
1373 items of a class, when you don't have a specific item of that class in
1374 mind.
1376 We allow access to properties. There will be no "id" property. The value
1377 accessed through the property will be the current value of the same name
1378 from the CGI form.
1380 There are several methods available on these wrapper objects:
1382 =========== =============================================================
1383 Method      Description
1384 =========== =============================================================
1385 properties  return a `hyperdb property wrapper`_ for all of this class's
1386             properties.
1387 list        lists all of the active (not retired) items in the class.
1388 csv         return the items of this class as a chunk of CSV text.
1389 propnames   lists the names of the properties of this class.
1390 filter      lists of items from this class, filtered and sorted by the
1391             current *request* filterspec/filter/sort/group args
1392 classhelp   display a link to a javascript popup containing this class'
1393             "help" template.
1394 submit      generate a submit button (and action hidden element)
1395 renderWith  render this class with the given template.
1396 history     returns 'New node - no history' :)
1397 is_edit_ok  is the user allowed to Edit the current class?
1398 is_view_ok  is the user allowed to View the current class?
1399 =========== =============================================================
1401 Note that if you have a property of the same name as one of the above
1402 methods, you'll need to access it using a python "item access"
1403 expression. For example::
1405    python:context['list']
1407 will access the "list" property, rather than the list method.
1410 Hyperdb item wrapper
1411 ::::::::::::::::::::
1413 Note: this is implemented by the ``roundup.cgi.templating.HTMLItem``
1414 class.
1416 This wrapper object provides access to a hyperb item.
1418 We allow access to properties. There will be no "id" property. The value
1419 accessed through the property will be the current value of the same name
1420 from the CGI form.
1422 There are several methods available on these wrapper objects:
1424 =============== ========================================================
1425 Method          Description
1426 =============== ========================================================
1427 submit          generate a submit button (and action hidden element)
1428 journal         return the journal of the current item (**not
1429                 implemented**)
1430 history         render the journal of the current item as HTML
1431 renderQueryForm specific to the "query" class - render the search form
1432                 for the query
1433 hasPermission   specific to the "user" class - determine whether the
1434                 user has a Permission
1435 is_edit_ok      is the user allowed to Edit the current item?
1436 is_view_ok      is the user allowed to View the current item?
1437 =============== ========================================================
1439 Note that if you have a property of the same name as one of the above
1440 methods, you'll need to access it using a python "item access"
1441 expression. For example::
1443    python:context['journal']
1445 will access the "journal" property, rather than the journal method.
1448 Hyperdb property wrapper
1449 ::::::::::::::::::::::::
1451 Note: this is implemented by subclasses of the
1452 ``roundup.cgi.templating.HTMLProperty`` class (``HTMLStringProperty``,
1453 ``HTMLNumberProperty``, and so on).
1455 This wrapper object provides access to a single property of a class. Its
1456 value may be either:
1458 1. if accessed through a `hyperdb item wrapper`_, then it's a value from
1459    the hyperdb
1460 2. if access through a `hyperdb class wrapper`_, then it's a value from
1461    the CGI form
1464 The property wrapper has some useful attributes:
1466 =============== ========================================================
1467 Attribute       Description
1468 =============== ========================================================
1469 _name           the name of the property
1470 _value          the value of the property if any - this is the actual
1471                 value retrieved from the hyperdb for this property
1472 =============== ========================================================
1474 There are several methods available on these wrapper objects:
1476 =========== ================================================================
1477 Method    Description
1478 =========== ================================================================
1479 plain       render a "plain" representation of the property. This method
1480             may take two arguments:
1482             escape
1483              If true, escape the text so it is HTML safe (default: no). The
1484              reason this defaults to off is that text is usually escaped
1485              at a later stage by the TAL commands, unless the "structure"
1486              option is used in the template. The following ``tal:content``
1487              expressions are all equivalent::
1488  
1489               "structure python:msg.content.plain(escape=1)"
1490               "python:msg.content.plain()"
1491               "msg/content/plain"
1492               "msg/content"
1494              Usually you'll only want to use the escape option in a
1495              complex expression.
1497             hyperlink
1498              If true, turn URLs, email addresses and hyperdb item
1499              designators in the text into hyperlinks (default: no). Note
1500              that you'll need to use the "structure" TAL option if you
1501              want to use this ``tal:content`` expression::
1502   
1503               "structure python:msg.content.plain(hyperlink=1)"
1505              Note also that the text is automatically HTML-escaped before
1506              the hyperlinking transformation.
1507 hyperlinked The same as msg.content.plain(hyperlink=1), but nicer::
1509               "structure msg/content/hyperlinked"
1511 field       render an appropriate form edit field for the property - for
1512             most types this is a text entry box, but for Booleans it's a
1513             tri-state yes/no/neither selection.
1514 stext       only on String properties - render the value of the property
1515             as StructuredText (requires the StructureText module to be
1516             installed separately)
1517 multiline   only on String properties - render a multiline form edit
1518             field for the property
1519 email       only on String properties - render the value of the property
1520             as an obscured email address
1521 confirm     only on Password properties - render a second form edit field
1522             for the property, used for confirmation that the user typed
1523             the password correctly. Generates a field with name
1524             "name:confirm".
1525 now         only on Date properties - return the current date as a new
1526             property
1527 reldate     only on Date properties - render the interval between the date
1528             and now
1529 local       only on Date properties - return this date as a new property
1530             with some timezone offset
1531 pretty      only on Interval properties - render the interval in a pretty
1532             format (eg. "yesterday")
1533 menu        only on Link and Multilink properties - render a form select
1534             list for this property
1535 reverse     only on Multilink properties - produce a list of the linked
1536             items in reverse order
1537 =========== ================================================================
1540 The request variable
1541 ~~~~~~~~~~~~~~~~~~~~
1543 Note: this is implemented by the ``roundup.cgi.templating.HTMLRequest``
1544 class.
1546 The request variable is packed with information about the current
1547 request.
1549 .. taken from ``roundup.cgi.templating.HTMLRequest`` docstring
1551 =========== ============================================================
1552 Variable    Holds
1553 =========== ============================================================
1554 form        the CGI form as a cgi.FieldStorage
1555 env         the CGI environment variables
1556 base        the base URL for this tracker
1557 user        a HTMLUser instance for this user
1558 classname   the current classname (possibly None)
1559 template    the current template (suffix, also possibly None)
1560 form        the current CGI form variables in a FieldStorage
1561 =========== ============================================================
1563 **Index page specific variables (indexing arguments)**
1565 =========== ============================================================
1566 Variable    Holds
1567 =========== ============================================================
1568 columns     dictionary of the columns to display in an index page
1569 show        a convenience access to columns - request/show/colname will
1570             be true if the columns should be displayed, false otherwise
1571 sort        index sort column (direction, column name)
1572 group       index grouping property (direction, column name)
1573 filter      properties to filter the index on
1574 filterspec  values to filter the index on
1575 search_text text to perform a full-text search on for an index
1576 =========== ============================================================
1578 There are several methods available on the request variable:
1580 =============== ========================================================
1581 Method          Description
1582 =============== ========================================================
1583 description     render a description of the request - handle for the
1584                 page title
1585 indexargs_form  render the current index args as form elements
1586 indexargs_url   render the current index args as a URL
1587 base_javascript render some javascript that is used by other components
1588                 of the templating
1589 batch           run the current index args through a filter and return a
1590                 list of items (see `hyperdb item wrapper`_, and
1591                 `batching`_)
1592 =============== ========================================================
1594 The form variable
1595 :::::::::::::::::
1597 The form variable is a bit special because it's actually a python
1598 FieldStorage object. That means that you have two ways to access its
1599 contents. For example, to look up the CGI form value for the variable
1600 "name", use the path expression::
1602    request/form/name/value
1604 or the python expression::
1606    python:request.form['name'].value
1608 Note the "item" access used in the python case, and also note the
1609 explicit "value" attribute we have to access. That's because the form
1610 variables are stored as MiniFieldStorages. If there's more than one
1611 "name" value in the form, then the above will break since
1612 ``request/form/name`` is actually a *list* of MiniFieldStorages. So it's
1613 best to know beforehand what you're dealing with.
1616 The db variable
1617 ~~~~~~~~~~~~~~~
1619 Note: this is implemented by the ``roundup.cgi.templating.HTMLDatabase``
1620 class.
1622 Allows access to all hyperdb classes as attributes of this variable. If
1623 you want access to the "user" class, for example, you would use::
1625   db/user
1626   python:db.user
1628 Also, the current id of the current user is available as
1629 ``db.curuserid``. This isn't so useful in templates (where you have
1630 ``request/user``), but it can be useful in detectors or interfaces.
1632 The access results in a `hyperdb class wrapper`_.
1635 The templates variable
1636 ~~~~~~~~~~~~~~~~~~~~~~
1638 Note: this is implemented by the ``roundup.cgi.templating.Templates``
1639 class.
1641 This variable doesn't have any useful methods defined. It supports being
1642 used in expressions to access the templates, and consequently the
1643 template macros. You may access the templates using the following path
1644 expression::
1646    templates/name
1648 or the python expression::
1650    templates[name]
1652 where "name" is the name of the template you wish to access. The
1653 template has one useful attribute, namely "macros". To access a specific
1654 macro (called "macro_name"), use the path expression::
1656    templates/name/macros/macro_name
1658 or the python expression::
1660    templates[name].macros[macro_name]
1663 The utils variable
1664 ~~~~~~~~~~~~~~~~~~
1666 Note: this is implemented by the
1667 ``roundup.cgi.templating.TemplatingUtils`` class, but it may be extended
1668 as described below.
1670 =============== ========================================================
1671 Method          Description
1672 =============== ========================================================
1673 Batch           return a batch object using the supplied list
1674 =============== ========================================================
1676 You may add additional utility methods by writing them in your tracker
1677 ``interfaces.py`` module's ``TemplatingUtils`` class. See `adding a time
1678 log to your issues`_ for an example. The TemplatingUtils class itself
1679 will have a single attribute, ``client``, which may be used to access
1680 the ``client.db`` when you need to perform arbitrary database queries.
1682 Batching
1683 ::::::::
1685 Use Batch to turn a list of items, or item ids of a given class, into a
1686 series of batches. Its usage is::
1688     python:utils.Batch(sequence, size, start, end=0, orphan=0,
1689     overlap=0)
1691 or, to get the current index batch::
1693     request/batch
1695 The parameters are:
1697 ========= ==============================================================
1698 Parameter  Usage
1699 ========= ==============================================================
1700 sequence  a list of HTMLItems
1701 size      how big to make the sequence.
1702 start     where to start (0-indexed) in the sequence.
1703 end       where to end (0-indexed) in the sequence.
1704 orphan    if the next batch would contain less items than this value,
1705           then it is combined with this batch
1706 overlap   the number of items shared between adjacent batches
1707 ========= ==============================================================
1709 All of the parameters are assigned as attributes on the batch object. In
1710 addition, it has several more attributes:
1712 =============== ========================================================
1713 Attribute       Description
1714 =============== ========================================================
1715 start           indicates the start index of the batch. *Note: unlike
1716                 the argument, is a 1-based index (I know, lame)*
1717 first           indicates the start index of the batch *as a 0-based
1718                 index*
1719 length          the actual number of elements in the batch
1720 sequence_length the length of the original, unbatched, sequence.
1721 =============== ========================================================
1723 And several methods:
1725 =============== ========================================================
1726 Method          Description
1727 =============== ========================================================
1728 previous        returns a new Batch with the previous batch settings
1729 next            returns a new Batch with the next batch settings
1730 propchanged     detect if the named property changed on the current item
1731                 when compared to the last item
1732 =============== ========================================================
1734 An example of batching::
1736  <table class="otherinfo">
1737   <tr><th colspan="4" class="header">Existing Keywords</th></tr>
1738   <tr tal:define="keywords db/keyword/list"
1739       tal:repeat="start python:range(0, len(keywords), 4)">
1740    <td tal:define="batch python:utils.Batch(keywords, 4, start)"
1741        tal:repeat="keyword batch" tal:content="keyword/name">
1742        keyword here</td>
1743   </tr>
1744  </table>
1746 ... which will produce a table with four columns containing the items of
1747 the "keyword" class (well, their "name" anyway).
1749 Displaying Properties
1750 ---------------------
1752 Properties appear in the user interface in three contexts: in indices,
1753 in editors, and as search arguments. For each type of property, there
1754 are several display possibilities. For example, in an index view, a
1755 string property may just be printed as a plain string, but in an editor
1756 view, that property may be displayed in an editable field.
1759 Index Views
1760 -----------
1762 This is one of the class context views. It is also the default view for
1763 classes. The template used is "*classname*.index".
1766 Index View Specifiers
1767 ~~~~~~~~~~~~~~~~~~~~~
1769 An index view specifier (URL fragment) looks like this (whitespace has
1770 been added for clarity)::
1772      /issue?status=unread,in-progress,resolved&
1773             topic=security,ui&
1774             :group=+priority&
1775             :sort==activity&
1776             :filters=status,topic&
1777             :columns=title,status,fixer
1779 The index view is determined by two parts of the specifier: the layout
1780 part and the filter part. The layout part consists of the query
1781 parameters that begin with colons, and it determines the way that the
1782 properties of selected items are displayed. The filter part consists of
1783 all the other query parameters, and it determines the criteria by which
1784 items are selected for display. The filter part is interactively
1785 manipulated with the form widgets displayed in the filter section. The
1786 layout part is interactively manipulated by clicking on the column
1787 headings in the table.
1789 The filter part selects the union of the sets of items with values
1790 matching any specified Link properties and the intersection of the sets
1791 of items with values matching any specified Multilink properties.
1793 The example specifies an index of "issue" items. Only items with a
1794 "status" of either "unread" or "in-progress" or "resolved" are
1795 displayed, and only items with "topic" values including both "security"
1796 and "ui" are displayed. The items are grouped by priority, arranged in
1797 ascending order; and within groups, sorted by activity, arranged in
1798 descending order. The filter section shows filters for the "status" and
1799 "topic" properties, and the table includes columns for the "title",
1800 "status", and "fixer" properties.
1802 Searching Views
1803 ---------------
1805 Note: if you add a new column to the ``:columns`` form variable
1806       potentials then you will need to add the column to the appropriate
1807       `index views`_ template so that it is actually displayed.
1809 This is one of the class context views. The template used is typically
1810 "*classname*.search". The form on this page should have "search" as its
1811 ``@action`` variable. The "search" action:
1813 - sets up additional filtering, as well as performing indexed text
1814   searching
1815 - sets the ``:filter`` variable correctly
1816 - saves the query off if ``:query_name`` is set.
1818 The search page should lay out any fields that you wish to allow the
1819 user to search on. If your schema contains a large number of properties,
1820 you should be wary of making all of those properties available for
1821 searching, as this can cause confusion. If the additional properties are
1822 Strings, consider having their value indexed, and then they will be
1823 searchable using the full text indexed search. This is both faster, and
1824 more useful for the end user.
1826 The two special form values on search pages which are handled by the
1827 "search" action are:
1829 :search_text
1830   Text with which to perform a search of the text index. Results from
1831   that search will be used to limit the results of other filters (using
1832   an intersection operation)
1833 :query_name
1834   If supplied, the search parameters (including :search_text) will be
1835   saved off as a the query item and registered against the user's
1836   queries property. Note that the *classic* template schema has this
1837   ability, but the *minimal* template schema does not.
1840 Item Views
1841 ----------
1843 The basic view of a hyperdb item is provided by the "*classname*.item"
1844 template. It generally has three sections; an "editor", a "spool" and a
1845 "history" section.
1848 Editor Section
1849 ~~~~~~~~~~~~~~
1851 The editor section is used to manipulate the item - it may be a static
1852 display if the user doesn't have permission to edit the item.
1854 Here's an example of a basic editor template (this is the default
1855 "classic" template issue item edit form - from the "issue.item.html"
1856 template)::
1858  <table class="form">
1859  <tr>
1860   <th nowrap>Title</th>
1861   <td colspan="3" tal:content="structure python:context.title.field(size=60)">title</td>
1862  </tr>
1863  
1864  <tr>
1865   <th nowrap>Priority</th>
1866   <td tal:content="structure context/priority/menu">priority</td>
1867   <th nowrap>Status</th>
1868   <td tal:content="structure context/status/menu">status</td>
1869  </tr>
1870  
1871  <tr>
1872   <th nowrap>Superseder</th>
1873   <td>
1874    <span tal:replace="structure python:context.superseder.field(showid=1, size=20)" />
1875    <span tal:replace="structure python:db.issue.classhelp('id,title')" />
1876    <span tal:condition="context/superseder">
1877     <br>View: <span tal:replace="structure python:context.superseder.link(showid=1)" />
1878    </span>
1879   </td>
1880   <th nowrap>Nosy List</th>
1881   <td>
1882    <span tal:replace="structure context/nosy/field" />
1883    <span tal:replace="structure python:db.user.classhelp('username,realname,address,phone')" />
1884   </td>
1885  </tr>
1886  
1887  <tr>
1888   <th nowrap>Assigned To</th>
1889   <td tal:content="structure context/assignedto/menu">
1890    assignedto menu
1891   </td>
1892   <td>&nbsp;</td>
1893   <td>&nbsp;</td>
1894  </tr>
1895  
1896  <tr>
1897   <th nowrap>Change Note</th>
1898   <td colspan="3">
1899    <textarea name=":note" wrap="hard" rows="5" cols="60"></textarea>
1900   </td>
1901  </tr>
1902  
1903  <tr>
1904   <th nowrap>File</th>
1905   <td colspan="3"><input type="file" name=":file" size="40"></td>
1906  </tr>
1907  
1908  <tr>
1909   <td>&nbsp;</td>
1910   <td colspan="3" tal:content="structure context/submit">
1911    submit button will go here
1912   </td>
1913  </tr>
1914  </table>
1917 When a change is submitted, the system automatically generates a message
1918 describing the changed properties. As shown in the example, the editor
1919 template can use the ":note" and ":file" fields, which are added to the
1920 standard changenote message generated by Roundup.
1923 Form values
1924 :::::::::::
1926 We have a number of ways to pull properties out of the form in order to
1927 meet the various needs of:
1929 1. editing the current item (perhaps an issue item)
1930 2. editing information related to the current item (eg. messages or
1931    attached files)
1932 3. creating new information to be linked to the current item (eg. time
1933    spent on an issue)
1935 In the following, ``<bracketed>`` values are variable, ":" may be one of
1936 ":" or "@", and other text ("required") is fixed.
1938 Properties are specified as form variables:
1940 ``<propname>``
1941   property on the current context item
1943 ``<designator>:<propname>``
1944   property on the indicated item (for editing related information)
1946 ``<classname>-<N>:<propname>``
1947   property on the Nth new item of classname (generally for creating new
1948   items to attach to the current item)
1950 Once we have determined the "propname", we check to see if it is one of
1951 the special form values:
1953 ``@required``
1954   The named property values must be supplied or a ValueError will be
1955   raised.
1957 ``@remove@<propname>=id(s)``
1958   The ids will be removed from the multilink property.
1960 ``:add:<propname>=id(s)``
1961   The ids will be added to the multilink property.
1963 ``:link:<propname>=<designator>``
1964   Used to add a link to new items created during edit. These are
1965   collected and returned in ``all_links``. This will result in an
1966   additional linking operation (either Link set or Multilink append)
1967   after the edit/create is done using ``all_props`` in ``_editnodes``.
1968   The <propname> on the current item will be set/appended the id of the
1969   newly created item of class <designator> (where <designator> must be
1970   <classname>-<N>).
1972 Any of the form variables may be prefixed with a classname or
1973 designator.
1975 Two special form values are supported for backwards compatibility:
1977 ``:note``
1978   create a message (with content, author and date), linked to the
1979   context item. This is ALWAYS designated "msg-1".
1980 ``:file``
1981   create a file, attached to the current item and any message created by
1982   :note. This is ALWAYS designated "file-1".
1985 Spool Section
1986 ~~~~~~~~~~~~~
1988 The spool section lists related information like the messages and files
1989 of an issue.
1991 TODO
1994 History Section
1995 ~~~~~~~~~~~~~~~
1997 The final section displayed is the history of the item - its database
1998 journal. This is generally generated with the template::
2000  <tal:block tal:replace="structure context/history" />
2002 *To be done:*
2004 *The actual history entries of the item may be accessed for manual
2005 templating through the "journal" method of the item*::
2007  <tal:block tal:repeat="entry context/journal">
2008   a journal entry
2009  </tal:block>
2011 *where each journal entry is an HTMLJournalEntry.*
2013 Defining new web actions
2014 ------------------------
2016 You may define new actions to be triggered by the ``@action`` form
2017 variable. These are added to the tracker ``interfaces.py`` as methods on
2018 the ``Client`` class. 
2020 Adding action methods takes three steps; first you `define the new
2021 action method`_, then you `register the action method`_ with the cgi
2022 interface so it may be triggered by the ``@action`` form variable.
2023 Finally you `use the new action`_ in your HTML form.
2025 See "`setting up a "wizard" (or "druid") for controlled adding of
2026 issues`_" for an example.
2029 Define the new action method
2030 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2032 The action methods have the following interface::
2034     def myActionMethod(self):
2035         ''' Perform some action. No return value is required.
2036         '''
2038 The *self* argument is an instance of your tracker ``instance.Client``
2039 class - thus it's mostly implemented by ``roundup.cgi.Client``. See the
2040 docstring of that class for details of what it can do.
2042 The method will typically check the ``self.form`` variable's contents.
2043 It may then:
2045 - add information to ``self.ok_message`` or ``self.error_message``
2046 - change the ``self.template`` variable to alter what the user will see
2047   next
2048 - raise Unauthorised, SendStaticFile, SendFile, NotFound or Redirect
2049   exceptions
2052 Register the action method
2053 ~~~~~~~~~~~~~~~~~~~~~~~~~~
2055 The method is now written, but isn't available to the user until you add
2056 it to the `instance.Client`` class ``actions`` variable, like so::
2058     actions = client.Class.actions + (
2059         ('myaction', 'myActionMethod'),
2060     )
2062 This maps the action name "myaction" to the action method we defined.
2065 Use the new action
2066 ~~~~~~~~~~~~~~~~~~
2068 In your HTML form, add a hidden form element like so::
2070   <input type="hidden" name="@action" value="myaction">
2072 where "myaction" is the name you registered in the previous step.
2075 Examples
2076 ========
2078 .. contents::
2079    :local:
2080    :depth: 1
2083 Adding a new field to the classic schema
2084 ----------------------------------------
2086 This example shows how to add a new constrained property (i.e. a
2087 selection of distinct values) to your tracker.
2090 Introduction
2091 ~~~~~~~~~~~~
2093 To make the classic schema of roundup useful as a TODO tracking system
2094 for a group of systems administrators, it needed an extra data field per
2095 issue: a category.
2097 This would let sysadmins quickly list all TODOs in their particular area
2098 of interest without having to do complex queries, and without relying on
2099 the spelling capabilities of other sysadmins (a losing proposition at
2100 best).
2103 Adding a field to the database
2104 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2106 This is the easiest part of the change. The category would just be a
2107 plain string, nothing fancy. To change what is in the database you need
2108 to add some lines to the ``open()`` function in ``dbinit.py``. Under the
2109 comment::
2111     # add any additional database schema configuration here
2113 add::
2115     category = Class(db, "category", name=String())
2116     category.setkey("name")
2118 Here we are setting up a chunk of the database which we are calling
2119 "category". It contains a string, which we are refering to as "name" for
2120 lack of a more imaginative title. (Since "name" is one of the properties
2121 that Roundup looks for on items if you do not set a key for them, it's
2122 probably a good idea to stick with it for new classes if at all
2123 appropriate.) Then we are setting the key of this chunk of the database
2124 to be that "name". This is equivalent to an index for database types.
2125 This also means that there can only be one category with a given name.
2127 Adding the above lines allows us to create categories, but they're not
2128 tied to the issues that we are going to be creating. It's just a list of
2129 categories off on its own, which isn't much use. We need to link it in
2130 with the issues. To do that, find the lines in the ``open()`` function
2131 in ``dbinit.py`` which set up the "issue" class, and then add a link to
2132 the category::
2134     issue = IssueClass(db, "issue", ... ,
2135         category=Multilink("category"), ... )
2137 The ``Multilink()`` means that each issue can have many categories. If
2138 you were adding something with a one-to-one relationship to issues (such
2139 as the "assignedto" property), use ``Link()`` instead.
2141 That is all you need to do to change the schema. The rest of the effort
2142 is fiddling around so you can actually use the new category.
2145 Populating the new category class
2146 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2148 If you haven't initialised the database with the roundup-admin
2149 "initialise" command, then you can add the following to the tracker
2150 ``dbinit.py`` in the ``init()`` function under the comment::
2152     # add any additional database create steps here - but only if you
2153     # haven't initialised the database with the admin "initialise" command
2155 Add::
2157      category = db.getclass('category')
2158      category.create(name="scipy", order="1")
2159      category.create(name="chaco", order="2")
2160      category.create(name="weave", order="3")
2162 If the database has already been initalised, then you need to use the
2163 ``roundup-admin`` tool::
2165      % roundup-admin -i <tracker home>
2166      Roundup <version> ready for input.
2167      Type "help" for help.
2168      roundup> create category name=scipy order=1
2169      1
2170      roundup> create category name=chaco order=1
2171      2
2172      roundup> create category name=weave order=1
2173      3
2174      roundup> exit...
2175      There are unsaved changes. Commit them (y/N)? y
2177 TODO: explain why order=1 in each case. Also, does key get set to "name"
2178 automatically when added via roundup-admin?
2181 Setting up security on the new objects
2182 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2184 By default only the admin user can look at and change objects. This
2185 doesn't suit us, as we want any user to be able to create new categories
2186 as required, and obviously everyone needs to be able to view the
2187 categories of issues for it to be useful.
2189 We therefore need to change the security of the category objects. This
2190 is also done in the ``open()`` function of ``dbinit.py``.
2192 There are currently two loops which set up permissions and then assign
2193 them to various roles. Simply add the new "category" to both lists::
2195     # new permissions for this schema
2196     for cl in 'issue', 'file', 'msg', 'user', 'category':
2197         db.security.addPermission(name="Edit", klass=cl,
2198             description="User is allowed to edit "+cl)
2199         db.security.addPermission(name="View", klass=cl,
2200             description="User is allowed to access "+cl)
2202     # Assign the access and edit permissions for issue, file and message
2203     # to regular users now
2204     for cl in 'issue', 'file', 'msg', 'category':
2205         p = db.security.getPermission('View', cl)
2206         db.security.addPermissionToRole('User', p)
2207         p = db.security.getPermission('Edit', cl)
2208         db.security.addPermissionToRole('User', p)
2210 So you are in effect doing the following (with 'cl' substituted by its
2211 value)::
2213     db.security.addPermission(name="Edit", klass='category',
2214         description="User is allowed to edit "+'category')
2215     db.security.addPermission(name="View", klass='category',
2216         description="User is allowed to access "+'category')
2218 which is creating two permission types; that of editing and viewing
2219 "category" objects respectively. Then the following lines assign those
2220 new permissions to the "User" role, so that normal users can view and
2221 edit "category" objects::
2223     p = db.security.getPermission('View', 'category')
2224     db.security.addPermissionToRole('User', p)
2226     p = db.security.getPermission('Edit', 'category')
2227     db.security.addPermissionToRole('User', p)
2229 This is all the work that needs to be done for the database. It will
2230 store categories, and let users view and edit them. Now on to the
2231 interface stuff.
2234 Changing the web left hand frame
2235 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2237 We need to give the users the ability to create new categories, and the
2238 place to put the link to this functionality is in the left hand function
2239 bar, under the "Issues" area. The file that defines how this area looks
2240 is ``html/page``, which is what we are going to be editing next.
2242 If you look at this file you can see that it contains a lot of
2243 "classblock" sections which are chunks of HTML that will be included or
2244 excluded in the output depending on whether the condition in the
2245 classblock is met. Under the end of the classblock for issue is where we
2246 are going to add the category code::
2248   <p class="classblock"
2249      tal:condition="python:request.user.hasPermission('View', 'category')">
2250    <b>Categories</b><br>
2251    <a tal:condition="python:request.user.hasPermission('Edit', 'category')"
2252       href="category?@template=item">New Category<br></a>
2253   </p>
2255 The first two lines is the classblock definition, which sets up a
2256 condition that only users who have "View" permission for the "category"
2257 object will have this section included in their output. Next comes a
2258 plain "Categories" header in bold. Everyone who can view categories will
2259 get that.
2261 Next comes the link to the editing area of categories. This link will
2262 only appear if the condition - that the user has "Edit" permissions for
2263 the "category" objects - is matched. If they do have permission then
2264 they will get a link to another page which will let the user add new
2265 categories.
2267 Note that if you have permission to *view* but not to *edit* categories,
2268 then all you will see is a "Categories" header with nothing underneath
2269 it. This is obviously not very good interface design, but will do for
2270 now. I just claim that it is so I can add more links in this section
2271 later on. However to fix the problem you could change the condition in
2272 the classblock statement, so that only users with "Edit" permission
2273 would see the "Categories" stuff.
2276 Setting up a page to edit categories
2277 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2279 We defined code in the previous section which let users with the
2280 appropriate permissions see a link to a page which would let them edit
2281 conditions. Now we have to write that page.
2283 The link was for the *item* template of the *category* object. This
2284 translates into Roundup looking for a file called ``category.item.html``
2285 in the ``html`` tracker directory. This is the file that we are going to
2286 write now.
2288 First we add an info tag in a comment which doesn't affect the outcome
2289 of the code at all, but is useful for debugging. If you load a page in a
2290 browser and look at the page source, you can see which sections come
2291 from which files by looking for these comments::
2293     <!-- category.item -->
2295 Next we need to add in the METAL macro stuff so we get the normal page
2296 trappings::
2298  <tal:block metal:use-macro="templates/page/macros/icing">
2299   <title metal:fill-slot="head_title">Category editing</title>
2300   <td class="page-header-top" metal:fill-slot="body_title">
2301    <h2>Category editing</h2>
2302   </td>
2303   <td class="content" metal:fill-slot="content">
2305 Next we need to setup up a standard HTML form, which is the whole
2306 purpose of this file. We link to some handy javascript which sends the
2307 form through only once. This is to stop users hitting the send button
2308 multiple times when they are impatient and thus having the form sent
2309 multiple times::
2311     <form method="POST" onSubmit="return submit_once()"
2312           enctype="multipart/form-data">
2314 Next we define some code which sets up the minimum list of fields that
2315 we require the user to enter. There will be only one field - "name" - so
2316 they better put something in it, otherwise the whole form is pointless::
2318     <input type="hidden" name="@required" value="name">
2320 To get everything to line up properly we will put everything in a table,
2321 and put a nice big header on it so the user has an idea what is
2322 happening::
2324     <table class="form">
2325      <tr><th class="header" colspan="2">Category</th></tr>
2327 Next, we need the field into which the user is going to enter the new
2328 category. The "context.name.field(size=60)" bit tells Roundup to
2329 generate a normal HTML field of size 60, and the contents of that field
2330 will be the "name" variable of the current context (which is
2331 "category"). The upshot of this is that when the user types something in
2332 to the form, a new category will be created with that name::
2334     <tr>
2335      <th nowrap>Name</th>
2336      <td tal:content="structure python:context.name.field(size=60)">
2337      name</td>
2338     </tr>
2340 Then a submit button so that the user can submit the new category::
2342     <tr>
2343      <td>&nbsp;</td>
2344      <td colspan="3" tal:content="structure context/submit">
2345       submit button will go here
2346      </td>
2347     </tr>
2349 Finally we finish off the tags we used at the start to do the METAL
2350 stuff::
2352   </td>
2353  </tal:block>
2355 So putting it all together, and closing the table and form we get::
2357  <!-- category.item -->
2358  <tal:block metal:use-macro="templates/page/macros/icing">
2359   <title metal:fill-slot="head_title">Category editing</title>
2360   <td class="page-header-top" metal:fill-slot="body_title">
2361    <h2>Category editing</h2>
2362   </td>
2363   <td class="content" metal:fill-slot="content">
2364    <form method="POST" onSubmit="return submit_once()"
2365          enctype="multipart/form-data">
2367     <input type="hidden" name="@required" value="name">
2369     <table class="form">
2370      <tr><th class="header" colspan="2">Category</th></tr>
2372      <tr>
2373       <th nowrap>Name</th>
2374       <td tal:content="structure python:context.name.field(size=60)">
2375       name</td>
2376      </tr>
2378      <tr>
2379       <td>&nbsp;</td>
2380       <td colspan="3" tal:content="structure context/submit">
2381        submit button will go here
2382       </td>
2383      </tr>
2384     </table>
2385    </form>
2386   </td>
2387  </tal:block>
2389 This is quite a lot to just ask the user one simple question, but there
2390 is a lot of setup for basically one line (the form line) to do its work.
2391 To add another field to "category" would involve one more line (well,
2392 maybe a few extra to get the formatting correct).
2395 Adding the category to the issue
2396 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2398 We now have the ability to create issues to our heart's content, but
2399 that is pointless unless we can assign categories to issues.  Just like
2400 the ``html/category.item.html`` file was used to define how to add a new
2401 category, the ``html/issue.item.html`` is used to define how a new issue
2402 is created.
2404 Just like ``category.issue.html`` this file defines a form which has a
2405 table to lay things out. It doesn't matter where in the table we add new
2406 stuff, it is entirely up to your sense of aesthetics::
2408    <th nowrap>Category</th>
2409    <td><span tal:replace="structure context/category/field" />
2410        <span tal:replace="structure db/category/classhelp" />
2411    </td>
2413 First, we define a nice header so that the user knows what the next
2414 section is, then the middle line does what we are most interested in.
2415 This ``context/category/field`` gets replaced by a field which contains
2416 the category in the current context (the current context being the new
2417 issue).
2419 The classhelp lines generate a link (labelled "list") to a popup window
2420 which contains the list of currently known categories.
2423 Searching on categories
2424 ~~~~~~~~~~~~~~~~~~~~~~~
2426 We can add categories, and create issues with categories. The next
2427 obvious thing that we would like to be able to do, would be to search
2428 for issues based on their category, so that, for example, anyone working
2429 on the web server could look at all issues in the category "Web".
2431 If you look for "Search Issues" in the 'html/page.html' file, you will
2432 find that it looks something like 
2433 ``<a href="issue?@template=search">Search Issues</a>``. This shows us
2434 that when you click on "Search Issues" it will be looking for a
2435 ``issue.search.html`` file to display. So that is the file that we will
2436 change.
2438 If you look at this file it should be starting to seem familiar, although it
2439 does use some new macros. You can add the new category search code anywhere you
2440 like within that form::
2442   <tr tal:define="name string:category;
2443                   db_klass string:category;
2444                   db_content string:name;">
2445     <th>Priority:</th>
2446     <td metal:use-macro="search_select"></td>
2447     <td metal:use-macro="column_input"></td>
2448     <td metal:use-macro="sort_input"></td>
2449     <td metal:use-macro="group_input"></td>
2450   </tr>
2452 The definitions in the <tr> opening tag are used by the macros:
2454 - search_select expands to a drop-down box with all categories using db_klass
2455   and db_content.
2456 - column_input expands to a checkbox for selecting what columns should be
2457   displayed.
2458 - sort_input expands to a radio button for selecting what property should be
2459   sorted on.
2460 - group_input expands to a radio button for selecting what property should be
2461   group on.
2463 The category search code above would expand to the following::
2465   <tr>
2466     <th>Category:</th>
2467     <td>
2468       <select name="category">
2469         <option value="">don't care</option>
2470         <option value="">------------</option>      
2471         <option value="1">scipy</option>
2472         <option value="2">chaco</option>
2473         <option value="3">weave</option>
2474       </select>
2475     </td>
2476     <td><input type="checkbox" name=":columns" value="category"></td>
2477     <td><input type="radio" name=":sort" value="category"></td>
2478     <td><input type="radio" name=":group" value="category"></td>
2479   </tr>
2481 Adding category to the default view
2482 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2484 We can now add categories, add issues with categories, and search for
2485 issues based on categories. This is everything that we need to do;
2486 however, there is some more icing that we would like. I think the
2487 category of an issue is important enough that it should be displayed by
2488 default when listing all the issues.
2490 Unfortunately, this is a bit less obvious than the previous steps. The
2491 code defining how the issues look is in ``html/issue.index.html``. This
2492 is a large table with a form down at the bottom for redisplaying and so
2493 forth. 
2495 Firstly we need to add an appropriate header to the start of the table::
2497     <th tal:condition="request/show/category">Category</th>
2499 The *condition* part of this statement is to avoid displaying the
2500 Category column if the user has selected not to see it.
2502 The rest of the table is a loop which will go through every issue that
2503 matches the display criteria. The loop variable is "i" - which means
2504 that every issue gets assigned to "i" in turn.
2506 The new part of code to display the category will look like this::
2508     <td tal:condition="request/show/category"
2509         tal:content="i/category"></td>
2511 The condition is the same as above: only display the condition when the
2512 user hasn't asked for it to be hidden. The next part is to set the
2513 content of the cell to be the category part of "i" - the current issue.
2515 Finally we have to edit ``html/page.html`` again. This time, we need to
2516 tell it that when the user clicks on "Unasigned Issues" or "All Issues",
2517 the category column should be included in the resulting list. If you
2518 scroll down the page file, you can see the links with lots of options.
2519 The option that we are interested in is the ``:columns=`` one which
2520 tells roundup which fields of the issue to display. Simply add
2521 "category" to that list and it all should work.
2524 Adding in state transition control
2525 ----------------------------------
2527 Sometimes tracker admins want to control the states that users may move
2528 issues to. You can do this by following these steps:
2530 1. make "status" a required variable. This is achieved by adding the
2531    following to the top of the form in the ``issue.item.html``
2532    template::
2534      <input type="hidden" name="@required" value="status">
2536    this will force users to select a status.
2538 2. add a Multilink property to the status class::
2540      stat = Class(db, "status", ... , transitions=Multilink('status'),
2541                   ...)
2543    and then edit the statuses already created, either:
2545    a. through the web using the class list -> status class editor, or
2546    b. using the roundup-admin "set" command.
2548 3. add an auditor module ``checktransition.py`` in your tracker's
2549    ``detectors`` directory, for example::
2551      def checktransition(db, cl, nodeid, newvalues):
2552          ''' Check that the desired transition is valid for the "status"
2553              property.
2554          '''
2555          if not newvalues.has_key('status'):
2556              return
2557          current = cl.get(nodeid, 'status')
2558          new = newvalues['status']
2559          if new == current:
2560              return
2561          ok = db.status.get(current, 'transitions')
2562          if new not in ok:
2563              raise ValueError, 'Status not allowed to move from "%s" to "%s"'%(
2564                  db.status.get(current, 'name'), db.status.get(new, 'name'))
2566      def init(db):
2567          db.issue.audit('set', checktransition)
2569 4. in the ``issue.item.html`` template, change the status editing bit
2570    from::
2572     <th nowrap>Status</th>
2573     <td tal:content="structure context/status/menu">status</td>
2575    to::
2577     <th nowrap>Status</th>
2578     <td>
2579      <select tal:condition="context/id" name="status">
2580       <tal:block tal:define="ok context/status/transitions"
2581                  tal:repeat="state db/status/list">
2582        <option tal:condition="python:state.id in ok"
2583                tal:attributes="
2584                     value state/id;
2585                     selected python:state.id == context.status.id"
2586                tal:content="state/name"></option>
2587       </tal:block>
2588      </select>
2589      <tal:block tal:condition="not:context/id"
2590                 tal:replace="structure context/status/menu" />
2591     </td>
2593    which displays only the allowed status to transition to.
2596 Displaying only message summaries in the issue display
2597 ------------------------------------------------------
2599 Alter the issue.item template section for messages to::
2601  <table class="messages" tal:condition="context/messages">
2602   <tr><th colspan="5" class="header">Messages</th></tr>
2603   <tr tal:repeat="msg context/messages">
2604    <td><a tal:attributes="href string:msg${msg/id}"
2605           tal:content="string:msg${msg/id}"></a></td>
2606    <td tal:content="msg/author">author</td>
2607    <td nowrap tal:content="msg/date/pretty">date</td>
2608    <td tal:content="msg/summary">summary</td>
2609    <td>
2610     <a tal:attributes="href string:?@remove@messages=${msg/id}&@action=edit">
2611     remove</a>
2612    </td>
2613   </tr>
2614  </table>
2616 Restricting the list of users that are assignable to a task
2617 -----------------------------------------------------------
2619 1. In your tracker's "dbinit.py", create a new Role, say "Developer"::
2621      db.security.addRole(name='Developer', description='A developer')
2623 2. Just after that, create a new Permission, say "Fixer", specific to
2624    "issue"::
2626      p = db.security.addPermission(name='Fixer', klass='issue',
2627          description='User is allowed to be assigned to fix issues')
2629 3. Then assign the new Permission to your "Developer" Role::
2631      db.security.addPermissionToRole('Developer', p)
2633 4. In the issue item edit page ("html/issue.item.html" in your tracker
2634    directory), use the new Permission in restricting the "assignedto"
2635    list::
2637     <select name="assignedto">
2638      <option value="-1">- no selection -</option>
2639      <tal:block tal:repeat="user db/user/list">
2640      <option tal:condition="python:user.hasPermission(
2641                                 'Fixer', context._classname)"
2642              tal:attributes="
2643                 value user/id;
2644                 selected python:user.id == context.assignedto"
2645              tal:content="user/realname"></option>
2646      </tal:block>
2647     </select>
2649 For extra security, you may wish to setup an auditor to enforce the
2650 Permission requirement (install this as "assignedtoFixer.py" in your
2651 tracker "detectors" directory)::
2653   def assignedtoMustBeFixer(db, cl, nodeid, newvalues):
2654       ''' Ensure the assignedto value in newvalues is a used with the
2655           Fixer Permission
2656       '''
2657       if not newvalues.has_key('assignedto'):
2658           # don't care
2659           return
2660   
2661       # get the userid
2662       userid = newvalues['assignedto']
2663       if not db.security.hasPermission('Fixer', userid, cl.classname):
2664           raise ValueError, 'You do not have permission to edit %s'%cl.classname
2666   def init(db):
2667       db.issue.audit('set', assignedtoMustBeFixer)
2668       db.issue.audit('create', assignedtoMustBeFixer)
2670 So now, if an edit action attempts to set "assignedto" to a user that
2671 doesn't have the "Fixer" Permission, the error will be raised.
2674 Setting up a "wizard" (or "druid") for controlled adding of issues
2675 ------------------------------------------------------------------
2677 1. Set up the page templates you wish to use for data input. My wizard
2678    is going to be a two-step process: first figuring out what category
2679    of issue the user is submitting, and then getting details specific to
2680    that category. The first page includes a table of help, explaining
2681    what the category names mean, and then the core of the form::
2683     <form method="POST" onSubmit="return submit_once()"
2684           enctype="multipart/form-data">
2685       <input type="hidden" name="@template" value="add_page1">
2686       <input type="hidden" name="@action" value="page1submit">
2688       <strong>Category:</strong>
2689       <tal:block tal:replace="structure context/category/menu" />
2690       <input type="submit" value="Continue">
2691     </form>
2693    The next page has the usual issue entry information, with the
2694    addition of the following form fragments::
2696     <form method="POST" onSubmit="return submit_once()"
2697           enctype="multipart/form-data"
2698           tal:condition="context/is_edit_ok"
2699           tal:define="cat request/form/category/value">
2701       <input type="hidden" name="@template" value="add_page2">
2702       <input type="hidden" name="@required" value="title">
2703       <input type="hidden" name="category" tal:attributes="value cat">
2704        .
2705        .
2706        .
2707     </form>
2709    Note that later in the form, I test the value of "cat" include form
2710    elements that are appropriate. For example::
2712     <tal:block tal:condition="python:cat in '6 10 13 14 15 16 17'.split()">
2713      <tr>
2714       <th nowrap>Operating System</th>
2715       <td tal:content="structure context/os/field"></td>
2716      </tr>
2717      <tr>
2718       <th nowrap>Web Browser</th>
2719       <td tal:content="structure context/browser/field"></td>
2720      </tr>
2721     </tal:block>
2723    ... the above section will only be displayed if the category is one
2724    of 6, 10, 13, 14, 15, 16 or 17.
2726 3. Determine what actions need to be taken between the pages - these are
2727    usually to validate user choices and determine what page is next. Now
2728    encode those actions in methods on the ``interfaces.Client`` class
2729    and insert hooks to those actions in the "actions" attribute on that
2730    class, like so::
2732     actions = client.Client.actions + (
2733         ('page1_submit', 'page1SubmitAction'),
2734     )
2736     def page1SubmitAction(self):
2737         ''' Verify that the user has selected a category, and then move
2738             on to page 2.
2739         '''
2740         category = self.form['category'].value
2741         if category == '-1':
2742             self.error_message.append('You must select a category of report')
2743             return
2744         # everything's ok, move on to the next page
2745         self.template = 'add_page2'
2747 4. Use the usual "new" action as the ``@action`` on the final page, and
2748    you're done (the standard context/submit method can do this for you).
2751 Using an external password validation source
2752 --------------------------------------------
2754 We have a centrally-managed password changing system for our users. This
2755 results in a UN*X passwd-style file that we use for verification of
2756 users. Entries in the file consist of ``name:password`` where the
2757 password is encrypted using the standard UN*X ``crypt()`` function (see
2758 the ``crypt`` module in your Python distribution). An example entry
2759 would be::
2761     admin:aamrgyQfDFSHw
2763 Each user of Roundup must still have their information stored in the
2764 Roundup database - we just use the passwd file to check their password.
2765 To do this, we add the following code to our ``Client`` class in the
2766 tracker home ``interfaces.py`` module::
2768     def verifyPassword(self, userid, password):
2769         # get the user's username
2770         username = self.db.user.get(userid, 'username')
2772         # the passwords are stored in the "passwd.txt" file in the
2773         # tracker home
2774         file = os.path.join(self.db.config.TRACKER_HOME, 'passwd.txt')
2776         # see if we can find a match
2777         for ent in [line.strip().split(':') for line in
2778                                             open(file).readlines()]:
2779             if ent[0] == username:
2780                 return crypt.crypt(password, ent[1][:2]) == ent[1]
2782         # user doesn't exist in the file
2783         return 0
2785 What this does is look through the file, line by line, looking for a
2786 name that matches.
2788 We also remove the redundant password fields from the ``user.item``
2789 template.
2792 Adding a "vacation" flag to users for stopping nosy messages
2793 ------------------------------------------------------------
2795 When users go on vacation and set up vacation email bouncing, you'll
2796 start to see a lot of messages come back through Roundup "Fred is on
2797 vacation". Not very useful, and relatively easy to stop.
2799 1. add a "vacation" flag to your users::
2801          user = Class(db, "user",
2802                     username=String(),   password=Password(),
2803                     address=String(),    realname=String(),
2804                     phone=String(),      organisation=String(),
2805                     alternate_addresses=String(),
2806                     roles=String(), queries=Multilink("query"),
2807                     vacation=Boolean())
2809 2. So that users may edit the vacation flags, add something like the
2810    following to your ``user.item`` template::
2812      <tr>
2813       <th>On Vacation</th> 
2814       <td tal:content="structure context/vacation/field">vacation</td> 
2815      </tr> 
2817 3. edit your detector ``nosyreactor.py`` so that the ``nosyreaction()``
2818    consists of::
2820     def nosyreaction(db, cl, nodeid, oldvalues):
2821         # send a copy of all new messages to the nosy list
2822         for msgid in determineNewMessages(cl, nodeid, oldvalues):
2823             try:
2824                 users = db.user
2825                 messages = db.msg
2827                 # figure the recipient ids
2828                 sendto = []
2829                 r = {}
2830                 recipients = messages.get(msgid, 'recipients')
2831                 for recipid in messages.get(msgid, 'recipients'):
2832                     r[recipid] = 1
2834                 # figure the author's id, and indicate they've received
2835                 # the message
2836                 authid = messages.get(msgid, 'author')
2838                 # possibly send the message to the author, as long as
2839                 # they aren't anonymous
2840                 if (db.config.MESSAGES_TO_AUTHOR == 'yes' and
2841                         users.get(authid, 'username') != 'anonymous'):
2842                     sendto.append(authid)
2843                 r[authid] = 1
2845                 # now figure the nosy people who weren't recipients
2846                 nosy = cl.get(nodeid, 'nosy')
2847                 for nosyid in nosy:
2848                     # Don't send nosy mail to the anonymous user (that
2849                     # user shouldn't appear in the nosy list, but just
2850                     # in case they do...)
2851                     if users.get(nosyid, 'username') == 'anonymous':
2852                         continue
2853                     # make sure they haven't seen the message already
2854                     if not r.has_key(nosyid):
2855                         # send it to them
2856                         sendto.append(nosyid)
2857                         recipients.append(nosyid)
2859                 # generate a change note
2860                 if oldvalues:
2861                     note = cl.generateChangeNote(nodeid, oldvalues)
2862                 else:
2863                     note = cl.generateCreateNote(nodeid)
2865                 # we have new recipients
2866                 if sendto:
2867                     # filter out the people on vacation
2868                     sendto = [i for i in sendto 
2869                               if not users.get(i, 'vacation', 0)]
2871                     # map userids to addresses
2872                     sendto = [users.get(i, 'address') for i in sendto]
2874                     # update the message's recipients list
2875                     messages.set(msgid, recipients=recipients)
2877                     # send the message
2878                     cl.send_message(nodeid, msgid, note, sendto)
2879             except roundupdb.MessageSendError, message:
2880                 raise roundupdb.DetectorError, message
2882    Note that this is the standard nosy reaction code, with the small
2883    addition of::
2885     # filter out the people on vacation
2886     sendto = [i for i in sendto if not users.get(i, 'vacation', 0)]
2888    which filters out the users that have the vacation flag set to true.
2891 Adding a time log to your issues
2892 --------------------------------
2894 We want to log the dates and amount of time spent working on issues, and
2895 be able to give a summary of the total time spent on a particular issue.
2897 1. Add a new class to your tracker ``dbinit.py``::
2899     # storage for time logging
2900     timelog = Class(db, "timelog", period=Interval())
2902    Note that we automatically get the date of the time log entry
2903    creation through the standard property "creation".
2905 2. Link to the new class from your issue class (again, in
2906    ``dbinit.py``)::
2908     issue = IssueClass(db, "issue", 
2909                     assignedto=Link("user"), topic=Multilink("keyword"),
2910                     priority=Link("priority"), status=Link("status"),
2911                     times=Multilink("timelog"))
2913    the "times" property is the new link to the "timelog" class.
2915 3. We'll need to let people add in times to the issue, so in the web
2916    interface we'll have a new entry field. This is a special field
2917    because unlike the other fields in the issue.item template, it
2918    affects a different item (a timelog item) and not the template's
2919    item, an issue. We have a special syntax for form fields that affect
2920    items other than the template default item (see the cgi 
2921    documentation on `special form variables`_). In particular, we add a
2922    field to capture a new timelog item's perdiod::
2924     <tr> 
2925      <th nowrap>Time Log</th> 
2926      <td colspan=3><input type="text" name="timelog-1@period" /> 
2927       <br />(enter as '3y 1m 4d 2:40:02' or parts thereof) 
2928      </td> 
2929     </tr> 
2930          
2931    and another hidden field that links that new timelog item (new
2932    because it's marked as having id "-1") to the issue item. It looks
2933    like this::
2935      <input type="hidden" name="@link@times" value="timelog-1" />
2937    On submission, the "-1" timelog item will be created and assigned a
2938    real item id. The "times" property of the issue will have the new id
2939    added to it.
2941 4. We want to display a total of the time log times that have been
2942    accumulated for an issue. To do this, we'll need to actually write
2943    some Python code, since it's beyond the scope of PageTemplates to
2944    perform such calculations. We do this by adding a method to the
2945    TemplatingUtils class in our tracker ``interfaces.py`` module::
2947     class TemplatingUtils:
2948         ''' Methods implemented on this class will be available to HTML
2949             templates through the 'utils' variable.
2950         '''
2951         def totalTimeSpent(self, times):
2952             ''' Call me with a list of timelog items (which have an
2953                 Interval "period" property)
2954             '''
2955             total = Interval('')
2956             for time in times:
2957                 total += time.period._value
2958             return total
2960    Replace the ``pass`` line as we did in step 4 above with the Client
2961    class. As indicated in the docstrings, we will be able to access the
2962    ``totalTimeSpent`` method via the ``utils`` variable in our
2963    templates.
2965 5. Display the time log for an issue::
2967      <table class="otherinfo" tal:condition="context/times">
2968       <tr><th colspan="3" class="header">Time Log
2969        <tal:block
2970             tal:replace="python:utils.totalTimeSpent(context.times)" />
2971       </th></tr>
2972       <tr><th>Date</th><th>Period</th><th>Logged By</th></tr>
2973       <tr tal:repeat="time context/times">
2974        <td tal:content="time/creation"></td>
2975        <td tal:content="time/period"></td>
2976        <td tal:content="time/creator"></td>
2977       </tr>
2978      </table>
2980    I put this just above the Messages log in my issue display. Note our
2981    use of the ``totalTimeSpent`` method which will total up the times
2982    for the issue and return a new Interval. That will be automatically
2983    displayed in the template as text like "+ 1y 2:40" (1 year, 2 hours
2984    and 40 minutes).
2986 8. If you're using a persistent web server - roundup-server or
2987    mod_python for example - then you'll need to restart that to pick up
2988    the code changes. When that's done, you'll be able to use the new
2989    time logging interface.
2991 Using a UN*X passwd file as the user database
2992 ---------------------------------------------
2994 On some systems the primary store of users is the UN*X passwd file. It
2995 holds information on users such as their username, real name, password
2996 and primary user group.
2998 Roundup can use this store as its primary source of user information,
2999 but it needs additional information too - email address(es), roundup
3000 Roles, vacation flags, roundup hyperdb item ids, etc. Also, "retired"
3001 users must still exist in the user database, unlike some passwd files in
3002 which the users are removed when they no longer have access to a system.
3004 To make use of the passwd file, we therefore synchronise between the two
3005 user stores. We also use the passwd file to validate the user logins, as
3006 described in the previous example, `using an external password
3007 validation source`_. We keep the users lists in sync using a fairly
3008 simple script that runs once a day, or several times an hour if more
3009 immediate access is needed. In short, it:
3011 1. parses the passwd file, finding usernames, passwords and real names,
3012 2. compares that list to the current roundup user list:
3014    a. entries no longer in the passwd file are *retired*
3015    b. entries with mismatching real names are *updated*
3016    c. entries only exist in the passwd file are *created*
3018 3. send an email to administrators to let them know what's been done.
3020 The retiring and updating are simple operations, requiring only a call
3021 to ``retire()`` or ``set()``. The creation operation requires more
3022 information though - the user's email address and their roundup Roles.
3023 We're going to assume that the user's email address is the same as their
3024 login name, so we just append the domain name to that. The Roles are
3025 determined using the passwd group identifier - mapping their UN*X group
3026 to an appropriate set of Roles.
3028 The script to perform all this, broken up into its main components, is
3029 as follows. Firstly, we import the necessary modules and open the
3030 tracker we're to work on::
3032     import sys, os, smtplib
3033     from roundup import instance, date
3035     # open the tracker
3036     tracker_home = sys.argv[1]
3037     tracker = instance.open(tracker_home)
3039 Next we read in the *passwd* file from the tracker home::
3041     # read in the users
3042     file = os.path.join(tracker_home, 'users.passwd')
3043     users = [x.strip().split(':') for x in open(file).readlines()]
3045 Handle special users (those to ignore in the file, and those who don't
3046 appear in the file)::
3048     # users to not keep ever, pre-load with the users I know aren't
3049     # "real" users
3050     ignore = ['ekmmon', 'bfast', 'csrmail']
3052     # users to keep - pre-load with the roundup-specific users
3053     keep = ['comment_pool', 'network_pool', 'admin', 'dev-team',
3054             'cs_pool', 'anonymous', 'system_pool', 'automated']
3056 Now we map the UN*X group numbers to the Roles that users should have::
3058     roles = {
3059      '501': 'User,Tech',  # tech
3060      '502': 'User',       # finance
3061      '503': 'User,CSR',   # customer service reps
3062      '504': 'User',       # sales
3063      '505': 'User',       # marketing
3064     }
3066 Now we do all the work. Note that the body of the script (where we have
3067 the tracker database open) is wrapped in a ``try`` / ``finally`` clause,
3068 so that we always close the database cleanly when we're finished. So, we
3069 now do all the work::
3071     # open the database
3072     db = tracker.open('admin')
3073     try:
3074         # store away messages to send to the tracker admins
3075         msg = []
3077         # loop over the users list read in from the passwd file
3078         for user,passw,uid,gid,real,home,shell in users:
3079             if user in ignore:
3080                 # this user shouldn't appear in our tracker
3081                 continue
3082             keep.append(user)
3083             try:
3084                 # see if the user exists in the tracker
3085                 uid = db.user.lookup(user)
3087                 # yes, they do - now check the real name for correctness
3088                 if real != db.user.get(uid, 'realname'):
3089                     db.user.set(uid, realname=real)
3090                     msg.append('FIX %s - %s'%(user, real))
3091             except KeyError:
3092                 # nope, the user doesn't exist
3093                 db.user.create(username=user, realname=real,
3094                     address='%s@ekit-inc.com'%user, roles=roles[gid])
3095                 msg.append('ADD %s - %s (%s)'%(user, real, roles[gid]))
3097         # now check that all the users in the tracker are also in our
3098         # "keep" list - retire those who aren't
3099         for uid in db.user.list():
3100             user = db.user.get(uid, 'username')
3101             if user not in keep:
3102                 db.user.retire(uid)
3103                 msg.append('RET %s'%user)
3105         # if we did work, then send email to the tracker admins
3106         if msg:
3107             # create the email
3108             msg = '''Subject: %s user database maintenance
3110             %s
3111             '''%(db.config.TRACKER_NAME, '\n'.join(msg))
3113             # send the email
3114             smtp = smtplib.SMTP(db.config.MAILHOST)
3115             addr = db.config.ADMIN_EMAIL
3116             smtp.sendmail(addr, addr, msg)
3118         # now we're done - commit the changes
3119         db.commit()
3120     finally:
3121         # always close the database cleanly
3122         db.close()
3124 And that's it!
3127 Using an LDAP database for user information
3128 -------------------------------------------
3130 A script that reads users from an LDAP store using
3131 http://python-ldap.sf.net/ and then compares the list to the users in the
3132 roundup user database would be pretty easy to write. You'd then have it run
3133 once an hour / day (or on demand if you can work that into your LDAP store
3134 workflow). See the example `Using a UN*X passwd file as the user database`_
3135 for more information about doing this.
3137 To authenticate off the LDAP store (rather than using the passwords in the
3138 roundup user database) you'd use the same python-ldap module inside an
3139 extension to the cgi interface. You'd do this by adding a method called
3140 "verifyPassword" to the Client class in your tracker's interfaces.py
3141 module. The method is implemented by default as::
3143     def verifyPassword(self, userid, password):
3144         ''' Verify the password that the user has supplied
3145         '''
3146         stored = self.db.user.get(self.userid, 'password')
3147         if password == stored:
3148             return 1
3149         if not password and not stored:
3150             return 1
3151         return 0
3153 So you could reimplement this as something like::
3155     def verifyPassword(self, userid, password):
3156         ''' Verify the password that the user has supplied
3157         '''
3158         # look up some unique LDAP information about the user
3159         username = self.db.user.get(self.userid, 'username')
3160         # now verify the password supplied against the LDAP store
3163 Enabling display of either message summaries or the entire messages
3164 -------------------------------------------------------------------
3166 This is pretty simple - all we need to do is copy the code from the
3167 example `displaying only message summaries in the issue display`_ into
3168 our template alongside the summary display, and then introduce a switch
3169 that shows either one or the other. We'll use a new form variable,
3170 ``@whole_messages`` to achieve this::
3172  <table class="messages" tal:condition="context/messages">
3173   <tal:block tal:condition="not:request/form/@whole_messages/value | python:0">
3174    <tr><th colspan="3" class="header">Messages</th>
3175        <th colspan="2" class="header">
3176          <a href="?@whole_messages=yes">show entire messages</a>
3177        </th>
3178    </tr>
3179    <tr tal:repeat="msg context/messages">
3180     <td><a tal:attributes="href string:msg${msg/id}"
3181            tal:content="string:msg${msg/id}"></a></td>
3182     <td tal:content="msg/author">author</td>
3183     <td nowrap tal:content="msg/date/pretty">date</td>
3184     <td tal:content="msg/summary">summary</td>
3185     <td>
3186      <a tal:attributes="href string:?@remove@messages=${msg/id}&@action=edit">remove</a>
3187     </td>
3188    </tr>
3189   </tal:block>
3191   <tal:block tal:condition="request/form/@whole_messages/value | python:0">
3192    <tr><th colspan="2" class="header">Messages</th>
3193        <th class="header">
3194          <a href="?@whole_messages=">show only summaries</a>
3195        </th>
3196    </tr>
3197    <tal:block tal:repeat="msg context/messages">
3198     <tr>
3199      <th tal:content="msg/author">author</th>
3200      <th nowrap tal:content="msg/date/pretty">date</th>
3201      <th style="text-align: right">
3202       (<a tal:attributes="href string:?@remove@messages=${msg/id}&@action=edit">remove</a>)
3203      </th>
3204     </tr>
3205     <tr><td colspan="3" tal:content="msg/content"></td></tr>
3206    </tal:block>
3207   </tal:block>
3208  </table>
3211 Blocking issues that depend on other issues
3212 -------------------------------------------
3214 We needed the ability to mark certain issues as "blockers" - that is,
3215 they can't be resolved until another issue (the blocker) they rely on is
3216 resolved. To achieve this:
3218 1. Create a new property on the issue Class,
3219    ``blockers=Multilink("issue")``. Edit your tracker's dbinit.py file.
3220    Where the "issue" class is defined, something like::
3222     issue = IssueClass(db, "issue", 
3223                     assignedto=Link("user"), topic=Multilink("keyword"),
3224                     priority=Link("priority"), status=Link("status"))
3226    add the blockers entry like so::
3228     issue = IssueClass(db, "issue", 
3229                     blockers=Multilink("issue"),
3230                     assignedto=Link("user"), topic=Multilink("keyword"),
3231                     priority=Link("priority"), status=Link("status"))
3233 2. Add the new "blockers" property to the issue.item edit page, using
3234    something like::
3236     <th nowrap>Waiting On</th>
3237     <td>
3238      <span tal:replace="structure python:context.blockers.field(showid=1,
3239                                   size=20)" />
3240      <span tal:replace="structure python:db.issue.classhelp('id,title')" />
3241      <span tal:condition="context/blockers"
3242            tal:repeat="blk context/blockers">
3243       <br>View: <a tal:attributes="href string:issue${blk/id}"
3244                    tal:content="blk/id"></a>
3245      </span>
3247    You'll need to fiddle with your item page layout to find an
3248    appropriate place to put it - I'll leave that fun part up to you.
3249    Just make sure it appears in the first table, possibly somewhere near
3250    the "superseders" field.
3252 3. Create a new detector module (attached) which enforces the rules:
3254    - issues may not be resolved if they have blockers
3255    - when a blocker is resolved, it's removed from issues it blocks
3257    The contents of the detector should be something like this::
3259     def blockresolution(db, cl, nodeid, newvalues):
3260         ''' If the issue has blockers, don't allow it to be resolved.
3261         '''
3262         if nodeid is None:
3263             blockers = []
3264         else:
3265             blockers = cl.get(nodeid, 'blockers')
3266         blockers = newvalues.get('blockers', blockers)
3268         # don't do anything if there's no blockers or the status hasn't
3269         # changed
3270         if not blockers or not newvalues.has_key('status'):
3271             return
3273         # get the resolved state ID
3274         resolved_id = db.status.lookup('resolved')
3276         # format the info
3277         u = db.config.TRACKER_WEB
3278         s = ', '.join(['<a href="%sissue%s">%s</a>'%(
3279                         u,id,id) for id in blockers])
3280         if len(blockers) == 1:
3281             s = 'issue %s is'%s
3282         else:
3283             s = 'issues %s are'%s
3285         # ok, see if we're trying to resolve
3286         if newvalues['status'] == resolved_id:
3287             raise ValueError, "This issue can't be resolved until %s resolved."%s
3289     def resolveblockers(db, cl, nodeid, newvalues):
3290         ''' When we resolve an issue that's a blocker, remove it from the
3291             blockers list of the issue(s) it blocks.
3292         '''
3293         if not newvalues.has_key('status'):
3294             return
3296         # get the resolved state ID
3297         resolved_id = db.status.lookup('resolved')
3299         # interesting?
3300         if newvalues['status'] != resolved_id:
3301             return
3303         # yes - find all the blocked issues, if any, and remove me from
3304         # their blockers list
3305         issues = cl.find(blockers=nodeid)
3306         for issueid in issues:
3307             blockers = cl.get(issueid, 'blockers')
3308             if nodeid in blockers:
3309                 blockers.remove(nodeid)
3310                 cl.set(issueid, blockers=blockers)
3313     def init(db):
3314         # might, in an obscure situation, happen in a create
3315         db.issue.audit('create', blockresolution)
3316         db.issue.audit('set', blockresolution)
3318         # can only happen on a set
3319         db.issue.react('set', resolveblockers)
3321    Put the above code in a file called "blockers.py" in your tracker's
3322    "detectors" directory.
3324 4. Finally, and this is an optional step, modify the tracker web page
3325    URLs so they filter out issues with any blockers. You do this by
3326    adding an additional filter on "blockers" for the value "-1". For
3327    example, the existing "Show All" link in the "page" template (in the
3328    tracker's "html" directory) looks like this::
3330      <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>
3332    modify it to add the "blockers" info to the URL (note, both the
3333    ":filter" *and* "blockers" values must be specified)::
3335      <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>
3337 That's it. You should now be able to set blockers on your issues. Note
3338 that if you want to know whether an issue has any other issues dependent
3339 on it (i.e. it's in their blockers list) you can look at the journal
3340 history at the bottom of the issue page - look for a "link" event to
3341 another issue's "blockers" property.
3344 -------------------
3346 Back to `Table of Contents`_
3348 .. _`Table of Contents`: index.html
3349 .. _`design documentation`: design.html